生活随笔
收集整理的這篇文章主要介紹了
Environment 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
date: 2019-06-21 11:35
status: draft
title: ‘Environment 的使用’
Environment 的使用有兩種方式
- 一種是通過@Autowired 的形式進行自動注入
- 另一種是通過實現 EnvironmentAware 接口的方式進行實現
通過@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 {@Resourceprivate Environment env
;@Beanpublic UserServiceImpl
userService(){System
.out
.println(env
);return new UserServiceImpl();}
}
產生這種現象的原因,根據測試的方式可以確定,在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
;@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();}
}
這種方式就避免了建立一個Environment 的ApplicationContext的方式,個人不推薦將其設置為ApplicationContext。
總結
以上是生活随笔為你收集整理的Environment 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。