[英]Why is @PostConstruct recognised in my case?
您能否告诉我为什么在我的情况下运行带有@PostContruct
注释的方法? 据我所知,Bean Post Processors处理带有@PostContruct
的方法。 如果要激活默认的CommonAnnotationBeanPostProcessor
,则需要在XML配置中添加<context:annotation-config/>
,但是我只想使用批注配置。 在我的情况下,配置中的@ComponentScan
指向该service
。 这意味着只有来自此程序包的类才能被实例化。
配置类:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "service")
public class AppConfig {
}
简单类:
package service;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class Simple {
@PostConstruct
private void sout(){
System.out.println("SOUT");
}
}
和启动器:
import config.AppConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.Simple;
public class Launcher {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Simple simple = ctx.getBean("simple", Simple.class);
}
}
该应用程序的输出为“ SOUT”。 您能否解释谁调用@PostContruct
方法以及如何调用?
AnnotationConfigApplicationContext
是基于XML的配置的替代方法。 当您使用它创建对象时,它首先创建对象和@Autowired
属性,然后调用@PostConstruct
方法。 这是编写您必须自己调用的setup()
或init()
方法的一种便捷选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.