beanFactory和applicationContext区别

发布时间 2023-03-26 19:38:12作者: 周公

继承关系

applicationContext接口继承beanFactory接口, 可以通过applicationContext获取beanFactory

同时也拓展了一下功能

 

 

功能一(国际化) 

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("message.xml");
                
    String rootHello = applicationContext.getMessage("hello", null, Locale.US);
    log.info("rootHello: " + rootHello);
    String chinaHello = applicationContext.getMessage("hello", null, Locale.CHINA);
    log.info("chinaHello: " + chinaHello);

 

功能二(获取资源) 

        Resource resource = applicationContext.getResource("message_en_US.properties");
        String filename = resource.getFilename();
        log.info("filename: " + filename);
        long contentLenth = resource.contentLength();
        log.info("contentLenth: " + contentLenth);

 

功能三(获取环境信息)

Environment environment = applicationContext.getEnvironment();
        String port = environment.getProperty("java.version");
        log.info("port: " + port);

 

功能一(事件处理) 

//调用类
        EmailEvent emailEvent = new EmailEvent("随便传的", "163@qq.com", "发个邮件");
        applicationContext.publishEvent(emailEvent);
        log.info("邮件发送完毕");


//事件类

public class EmailEvent extends ApplicationEvent {
    private String address;
    private String content;

    public EmailEvent(Object source, String address, String content) {
        super(source);
        this.content = content;
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }



//监听器
public class EmailListener implements ApplicationListener {


    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        EmailEvent emailEvent = (EmailEvent) applicationEvent;
        log.info("emailEvent.getAddress(): " + emailEvent.getAddress() + "  emailEvent.getContent(): " + emailEvent.getContent());
    }
}