首页 > 解决方案 > 使用 new 关键字创建对象时如何调用 PostConstruct 方法

问题描述

我有一个类Banana,它有一个@PostConstruct我想在创建类对象后运行的方法。我正在使用这些调用创建此类的对象

Cat cat = new Cat();
Banana b = new Banana(cat);

因此,从日志中我了解到,在创建对象@PostConstruct时不会调用此方法。Banana我认为我实施的方式不是正确的用法。有人可以指导我如何正确实现这一点,因为这是我使用 Spring Boot 进行 Java 项目的第一个任务。我需要在Banana创建对象后运行该设置代码,所以除了@PostConstruct

@Slf4j
public class Banana {
    public Banana(Cat cat) {
        this.cat = cat;
    }
    private Cat cat;

    @PostConstruct
    public void setup() {
        // some code
    }

    public void execute() {
        // some code
    }
}

标签: javaspring-bootpostconstruct

解决方案


当对象由 spring 本身创建时,spring支持的所有注释(@PostConstruct、和许多其他注释)都适用。在这种情况下,spring 可以分析类、处理注释等。@PreDestroy@Autowired

当你自己实例化时(new Banana())——spring 甚至不知道你的对象存在,因此不能调用它的任何方法,所以你被迫自己做。所以是的,在这种情况下,您将不得不@PostConstruct手动调用带有注释的方法,这意味着@PostConstruct注释非常无用,可以完全省略。


推荐阅读