生活随笔
收集整理的這篇文章主要介紹了
Environment 的使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
date: 2019-06-21 11:35
status: draft
title: ‘Environment 的使用’
Environment 的使用有兩種方式
- 一種是通過@Autowired 的形式進(jìn)行自動(dòng)注入
- 另一種是通過實(shí)現(xiàn) EnvironmentAware 接口的方式進(jìn)行實(shí)現(xiàn)
通過@Autowired 的形式進(jìn)行注入
官方網(wǎng)站的樣例
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 {@Resourceprivate Environment env
;@Beanpublic UserServiceImpl
userService(){System
.out
.println(env
);return new UserServiceImpl();}
}
產(chǎn)生這種現(xiàn)象的原因,根據(jù)測(cè)試的方式可以確定,在Spring整合mybatis的時(shí)候,BeanFactoryPostProcessor 這個(gè)bean比較早的被創(chuàng)建,這個(gè)時(shí)候的private Environment evn 還沒有被賦值,而這個(gè)bean 有沒有表明要依賴 evn 而創(chuàng)建,那么就傳進(jìn)一個(gè)null 變量,
首先,我想想到的是通過構(gòu)造器或者set方法注入,但是這種想法被打斷了,因?yàn)檫@個(gè)bean還會(huì)再注入,比較亂沒有調(diào)通。
沒有辦法了,換成EnvironmentAware 接口的形式,調(diào)通了。
2. 通過實(shí)現(xiàn)EnvironmentAware 接口的形式實(shí)現(xiàn)
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
;@Overridepublic void setEnvironment(Environment environment
) {this.env
=environment
;}@Beanpublic UserServiceImpl
userService(){System
.out
.println(env
);return new UserServiceImpl();}@Beanpublic TestBeanFactoryPostProcessor
testBeanFactoryPostProcessor(){System
.out
.println(env
);return new TestBeanFactoryPostProcessor();}
}
這種方式就避免了建立一個(gè)Environment 的ApplicationContext的方式,個(gè)人不推薦將其設(shè)置為ApplicationContext。
總結(jié)
以上是生活随笔為你收集整理的Environment 的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。