使用new关键字创建对象时如何调用PostConstruct方法

0 java postconstruct spring-boot

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

Cat cat = new Cat();
Banana b = new Banana(cat);
Run Code Online (Sandbox Code Playgroud)

因此,从日志中我了解到创建对象@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
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 5

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

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