Environmentの使用
10795 ワード
date:2019-06-21 11:35 status:draft title:‘Environmentの使用’
Environmentの使用には2つの方法があります@Autowired形式による自動注入 は、EnvironmentAwareインタフェースを実装することによって、 を実装する.@Autowired形式で公式サイトに注入したサンプル
このような現象が発生した原因は、Springがmybatisを統合したとき、BeanFactoryPostProcessorというbeanが比較的早く作成され、このときのprivate Environment evnはまだ付与されていないが、このbeanがevnに依存して作成することを示しているかどうかは、null変数に伝わり、まず、私が考えたのはコンストラクタやset法で注入することですが、この考えは中断されました.このbeanはまた注入されるので、混乱しています.仕方なく、EnvironmentAwareインタフェースの形に変えて、チューニングしました.2.EnvironmentAwareインタフェースを実現する形で実現
これにより、個人的にはApplicationContextとして設定することを推奨しないEnvironmentのApplicationContextを確立する方法が回避されます.
Environmentの使用には2つの方法があります
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();
}
}
これにより、個人的にはApplicationContextとして設定することを推奨しないEnvironmentのApplicationContextを確立する方法が回避されます.