繁体   English   中英

为什么我可以识别@PostConstruct?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM