Java 为什么@PostConstruct在我的案例中得到认可?
你能告诉我为什么在我的例子中会运行一个带有Java 为什么@PostConstruct在我的案例中得到认可?,java,spring,spring-annotations,Java,Spring,Spring Annotations,你能告诉我为什么在我的例子中会运行一个带有@postcontract注释的方法吗?据我所知,带有@postcontract的方法是由Bean后处理器处理的。如果要激活默认的CommonAnnotationBeanPostProcessor,需要在XML配置中添加,但我只想使用注释配置。在我的例子中,配置中的@ComponentScan指向服务。这意味着只有来自这个包的类才可能被实例化 配置类: package config; import org.springframework.context
@postcontract
注释的方法吗?据我所知,带有@postcontract
的方法是由Bean后处理器处理的。如果要激活默认的CommonAnnotationBeanPostProcessor
,需要在XML配置中添加
,但我只想使用注释配置。在我的例子中,配置中的@ComponentScan
指向服务
。这意味着只有来自这个包的类才可能被实例化
配置类:
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”。您能否解释是谁调用了
@postcontract
方法以及如何调用该方法?注释配置应用程序上下文
是基于XML的配置的替代方案。使用它创建对象时,它首先创建对象和@Autowired
属性,然后调用@PostConstruct
方法。它是编写setup()
或init()
方法的一个方便的替代方法,您必须自己调用该方法。因为您使用AnnotationConfigApplicationContext
自动假定您要处理所有注释。对于XML驱动的配置,您所说的是正确的,因为默认情况下没有启用注释处理。