Environment 的使用


date: 2019-06-21 11:35
status: draft
title: ‘Environment 的使用’

Environment 的使用有两种方式

  • 一种是通过@Autowired 的形式进行自动注入
  • 另一种是通过实现 EnvironmentAware 接口的方式进行实现
  1. 通过@Autowired 的形式进行注入
    官方网站的样例
package org.exam.config;
import org.exam.service.TestBeanFactoryPostProcessor;
import org.exam.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import javax.annotation.Resource;
@Configuration
@ComponentScan(basePackages = {"org.exam.service"})
@PropertySource("classpath:config.properties")
public class AppConfigOld {
    @Resource
    private Environment env;
    @Bean
    public UserServiceImpl userService(){
        System.out.println(env);
        return new UserServiceImpl();
    }
    /*
    未加入这个BeanFactoryPostProcessor一切都很正常,一旦加入这个@Bean,env就变为null
    @Bean
    public TestBeanFactoryPostProcessor testBeanFactoryPostProcessor(){
        System.out.println(env);
        return new TestBeanFactoryPostProcessor();
    }
    */
}

产生这种现象的原因,根据测试的方式可以确定,在Spring整合mybatis的时候,BeanFactoryPostProcessor 这个bean比较早的被创建,这个时候的private Environment evn 还没有被赋值,而这个bean 有没有表明要依赖 evn 而创建,那么就传进一个null 变量,
首先,我想想到的是通过构造器或者set方法注入,但是这种想法被打断了,因为这个bean还会再注入,比较乱没有调通。
没有办法了,换成EnvironmentAware 接口的形式,调通了。
2. 通过实现EnvironmentAware 接口的形式实现

package org.exam.config;
import org.exam.service.TestBeanFactoryPostProcessor;
import org.exam.service.UserServiceImpl;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@ComponentScan(basePackages = {"org.exam.service"})
@PropertySource("classpath:config.properties")
public class AppConfig implements EnvironmentAware {
    private Environment env;
    @Override
    public void setEnvironment(Environment environment) {
        this.env=environment;
    }
    @Bean
    public UserServiceImpl userService(){
        System.out.println(env);
        return new UserServiceImpl();
    }
    @Bean
    public TestBeanFactoryPostProcessor testBeanFactoryPostProcessor(){
        System.out.println(env);
        return new TestBeanFactoryPostProcessor();
    }
}

这种方式就避免了建立一个Environment 的ApplicationContext的方式,个人不推荐将其设置为ApplicationContext。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值