17、Bean的生命周期
-
bean的生命周期:bean的創(chuàng)建—初始化—銷毀的過程
-
容器負(fù)責(zé)管理bean的生命周期
-
我們可以自定義初始化和銷毀方法,容器在bean進(jìn)行到當(dāng)前生命周期的時候來調(diào)用我們自定義的初始化和銷毀方法
-
構(gòu)造(對象創(chuàng)建)
單實(shí)例:在容器啟動時創(chuàng)建對象
多實(shí)例:在每次獲取的時候創(chuàng)建對象 -
初始化:
單實(shí)例:容器 關(guān)閉的時候
多實(shí)例:容器不會管理這個bean,容器不會調(diào)用銷毀方法,如果需要銷毀必須使用手動調(diào)用。
指定初始化和銷毀方法有三種
1、使用@Bean(initMethod = “init”,destroyMethod = “destory”)
2、通過讓Bean實(shí)現(xiàn)InitializingBean接口來定義初始化邏輯 ,DisposableBean接口來銷毀bean
3、@PostConstruct、@PreDestory注解初始化和銷毀方式
4、@BeanPostProcessor后置處理器,在bean初始化進(jìn)行相應(yīng)操作
18、@Bean(initMethod = “init”,destroyMethod = “destory”)指定初始化和銷毀方式
1)指定初始化和銷毀方式
使用@Bean(initMethod = “init”,destroyMethod = “destory”)
多實(shí)例bean的銷毀,由用戶自定義,容器不再管理
指定前
創(chuàng)建bean并設(shè)置初始化和銷毀方法
public class Car {
public Car(){
System.out.println("car is constructor........");
}
public void init(){
System.out.println("car is inited........");
}
public void destory(){
System.out.println("car is destoried.....");
}
}
創(chuàng)建配置類,并配置bean
@Configuration
public class MainConfigOfLifeCycle {
@Bean
public Car car(){
return new Car();
}
}
測試類
public class testLife {
//創(chuàng)建ioc容器
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
@Test
public void testLifeCycle(){
System.out.println(" 容器創(chuàng)建完成");
}
}
測試結(jié)果
car is constructor........
容器創(chuàng)建完成
指定后
創(chuàng)建配置類,并配置bean
注意: @Bean(initMethod = “init”,destroyMethod = “destory”)
@Configuration
public class MainConfigOfLifeCycle {
@Bean(initMethod = "init",destroyMethod = "destory")
public Car car(){
return new Car();
}
}
測試類
public class testLife {
//創(chuàng)建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
@Test
public void testLifeCycle(){
System.out.println("容器創(chuàng)建完成");
applicationContext.close();
}
}
測試結(jié)果:
car is constructor........
car is inited........
容器創(chuàng)建完成
car is destoried.....
19、InitializingBean接口定義初始化和銷毀方式
2)通過讓Bean實(shí)現(xiàn)InitializingBean接口來定義初始化邏輯 ,DisposableBean接口來銷毀bean
創(chuàng)建自定義bean,并實(shí)現(xiàn)InitializingBean、DisposableBean接口,同時改寫destory()和afterPropertiesSet()方法
@Component
public class Cat implements InitializingBean, DisposableBean {
public Cat() {
System.out.println("cat is generated.....");
}
//銷毀方法
@Override
public void destroy() throws Exception {
System.out.println("cat is destoried ......");
}
//初始化方法
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat is inited ......");
}
}
修改配置類
@Configuration
@ComponentScan("com.atguigu")
public class MainConfigOfLifeCycle {
@Bean(initMethod = "init",destroyMethod = "destory")
public Car car(){
return new Car();
}
}
測試類
public class testLife {
//創(chuàng)建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
@Test
public void testLifeCycle(){
System.out.println("容器創(chuàng)建完成");
applicationContext.getBean("cat");
applicationContext.close();
}
}
測試結(jié)果
cat is generated.....
cat is inited ......
car is constructor........
car is inited........
容器創(chuàng)建完成
car is destoried.....
cat is destoried ......
20、@PostConstruct、@PreDestory注解初始化和銷毀方式
3)通過讓Bean實(shí)現(xiàn)PostConstruct接口來定義初始化邏輯 ,PreDestory接口來銷毀bean
@PostConstuct:在bean創(chuàng)建完成并且屬性賦值完成初始化方法,作用在方法上
@preDestory:再容器銷毀bean之前通知我們進(jìn)行清理工作
比較好的一篇文章
@PostConstruct詳解
**創(chuàng)建bean類并添加相應(yīng)注解 **
@Component
public class Dog {
public Dog() {
System.out.println("dog is generated");
}
//對象創(chuàng)建并賦值之后調(diào)用
@PostConstruct
public void init(){
System.out.println("dog is constructed ......");
}
//容器移除對象之前
@PreDestroy
public void destory(){
System.out.println("dog is destoried ......");
}
}
測試類
public class testLife {
//創(chuàng)建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
@Test
public void testLifeCycle(){
System.out.println("容器創(chuàng)建完成");
//applicationContext.getBean("cat");
applicationContext.close();
}
}
測試結(jié)果
cat is generated.....
cat is inited ......
dog is generated
car is constructor........
car is inited........
容器創(chuàng)建完成
car is destoried.....
cat is destoried ......
21、@BeanPostProcessor后置處理器
4)@BeanPostProcessor后置處理器,在bean初始化進(jìn)行相應(yīng)操作,包括:
postProcessBeforeInitialization:在初始化之前工作
postProcessAfterInitialization:在初始化之后工作(調(diào)用)
具體來說需要事項(xiàng)BeanPostProcessor接口,并改寫postProcessBeforeInitialization(Object o, String s)、postProcessAfterInitialization(Object o, String s)方法
創(chuàng)建自定義后置處理器
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化完成前工作調(diào)用"+beanName+"=>"+bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化完成后工作調(diào)用"+beanName+"=>"+bean);
return bean;
}
}
測試類
public class testLife {
//創(chuàng)建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
@Test
public void testLifeCycle(){
System.out.println("容器創(chuàng)建完成");
//applicationContext.getBean("cat");
applicationContext.close();
}
}
測試結(jié)果
初始化完成前工作調(diào)用org.springframework.context.event.internalEventListenerProcessor=>org.springframework.context.event.EventListenerMethodProcessor@4b5189ac
初始化完成后工作調(diào)用org.springframework.context.event.internalEventListenerProcessor=>org.springframework.context.event.EventListenerMethodProcessor@4b5189ac
初始化完成前工作調(diào)用org.springframework.context.event.internalEventListenerFactory=>org.springframework.context.event.DefaultEventListenerFactory@704deff2
初始化完成后工作調(diào)用org.springframework.context.event.internalEventListenerFactory=>org.springframework.context.event.DefaultEventListenerFactory@704deff2
初始化完成前工作調(diào)用mainConfigOfLifeCycle=>com.atguigu.config.MainConfigOfLifeCycle$$EnhancerBySpringCGLIB$$9bbbd82c@2b9ed6da
初始化完成后工作調(diào)用mainConfigOfLifeCycle=>com.atguigu.config.MainConfigOfLifeCycle$$EnhancerBySpringCGLIB$$9bbbd82c@2b9ed6da
cat is generated.....
初始化完成前工作調(diào)用cat=>com.atguigu.bean.Cat@59d4cd39
cat is inited ......
初始化完成后工作調(diào)用cat=>com.atguigu.bean.Cat@59d4cd39
dog is generated
初始化完成前工作調(diào)用dog=>com.atguigu.bean.Dog@1187c9e8
初始化完成后工作調(diào)用dog=>com.atguigu.bean.Dog@1187c9e8
初始化完成前工作調(diào)用mainConfig=>com.atguigu.config.MainConfig$$EnhancerBySpringCGLIB$$201ea2bd@6d7fc27
初始化完成后工作調(diào)用mainConfig=>com.atguigu.config.MainConfig$$EnhancerBySpringCGLIB$$201ea2bd@6d7fc27
初始化完成前工作調(diào)用bookController=>com.atguigu.controller.BookController@135606db
初始化完成后工作調(diào)用bookController=>com.atguigu.controller.BookController@135606db
初始化完成前工作調(diào)用bookDAO=>com.atguigu.dao.BookDAO@6c372fe6
初始化完成后工作調(diào)用bookDAO=>com.atguigu.dao.BookDAO@6c372fe6
初始化完成前工作調(diào)用bookService=>com.atguigu.service.BookService@2a3888c1
初始化完成后工作調(diào)用bookService=>com.atguigu.service.BookService@2a3888c1
初始化完成前工作調(diào)用com.atguigu.bean.Color=>com.atguigu.bean.Color@4167d97b
初始化完成后工作調(diào)用com.atguigu.bean.Color=>com.atguigu.bean.Color@4167d97b
初始化完成前工作調(diào)用com.atguigu.bean.Red=>com.atguigu.bean.Red@14fa86ae
初始化完成后工作調(diào)用com.atguigu.bean.Red=>com.atguigu.bean.Red@14fa86ae
初始化完成前工作調(diào)用com.atguigu.bean.Blue=>com.atguigu.bean.Blue@6e15fe2
初始化完成后工作調(diào)用com.atguigu.bean.Blue=>com.atguigu.bean.Blue@6e15fe2
初始化完成前工作調(diào)用com.atguigu.bean.Yellow=>com.atguigu.bean.Yellow@68f1b17f
初始化完成后工作調(diào)用com.atguigu.bean.Yellow=>com.atguigu.bean.Yellow@68f1b17f
初始化完成前工作調(diào)用female=>Person{name='wanger', age=23}
初始化完成后工作調(diào)用female=>Person{name='wanger', age=23}
初始化完成前工作調(diào)用colorFactoryBean=>com.atguigu.bean.ColorFactory@7cbd9d24
初始化完成后工作調(diào)用colorFactoryBean=>com.atguigu.bean.ColorFactory@7cbd9d24
初始化完成前工作調(diào)用rainbow=>com.atguigu.bean.RainBow@1b45c0e
初始化完成后工作調(diào)用rainbow=>com.atguigu.bean.RainBow@1b45c0e
car is constructor........
初始化完成前工作調(diào)用car=>com.atguigu.bean.Car@73a8da0f
car is inited........
初始化完成后工作調(diào)用car=>com.atguigu.bean.Car@73a8da0f
容器創(chuàng)建完成
car is destoried.....
cat is destoried ......
22、@Value為屬性賦值
在bean類的屬性上直接使用@Value注解來賦值
創(chuàng)建bean類(pojo類)
public class Person {
//value的值可以是1、基本數(shù)據(jù)類型值,2、可以寫表達(dá)式如#{},3、可以用${}取出配置文件的值(在運(yùn)行的環(huán)境變量中的值)
@Value("張三")
private String name;
@Value("#{23+4}")
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
創(chuàng)建配置類
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
測試類
public class TestAno {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfigOfPropertyValues .class);
@Test
public void testProperty(){
printBeans(applicationContext);
System.out.println("====");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
}
測試結(jié)果
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfigOfPropertyValues
person
====
Person{name='張三', age=27}
23、@PropertySource加載外部配置文件屬性賦值
需要加載外部配置文件,讀取配置文件中 的k/v,保存到運(yùn)行中的環(huán)境變量中
1、創(chuàng)建配置文件,在文件中創(chuàng)建若干鍵值對
創(chuàng)建文件 person.properties
person.name=zhangsanfeng
2、在配置類中使用@PropertySource指定配置文件
注意:@PropertySource(value={“classpath:/person.properties”})
//加載外部配置文件,讀取配置文件中 的k/v,保存到運(yùn)行中的環(huán)境變量中
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
3、bean類中引用相應(yīng)的值
注意:
@Value(“${person.name}”)
private String name;
public class Person {
//value的值可以是1、基本數(shù)據(jù)類型值,2、可以寫表達(dá)式如#{},3、可以用${}取出配置文件的值(在運(yùn)行的環(huán)境變量中的值)
@Value("${person.name}")
private String name;
@Value("#{23+4}")
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4、測試類
public class TestAno {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfigOfPropertyValues .class);
@Test
public void testProperty(){
printBeans(applicationContext);
System.out.println("====");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property=environment.getProperty("person.name");
System.out.println(property);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
}
5、測試結(jié)果
注意:Person{name=‘zhangsanfeng’, age=27}
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfigOfPropertyValues
person
====
Person{name='zhangsanfeng', age=27}
zhangsanfeng
24、@Autowired&自動裝配
自動裝配:Spring利用依賴注入(DI),完成對IOC容器中各個組件的依賴關(guān)系賦值
1)@Autowired
一個組件需要使用到另外一個組件,直接對被使用的組件上添加@Autowired注解就可以注入這個組件。它:
- 默認(rèn)優(yōu)先按照類型去容器內(nèi)找到對應(yīng)的組件:如: BookDAO bookDAO =
applicationContext.getBean(BookDAO.class); - 如果有多個同類型的組件,再將屬性名作為組件的id去容器中查找(沒測試出來,總是報找到兩個bean)
dao類
@Repository
public class BookDAO {
}
service類
@Service
public class BookService {
@Autowired
private BookDAO bookDao;
public void print(){
System.out.println(bookDao);
}
}
controller
@Controller
public class BookController {
@Autowired
private BookService bookService;
}
配置類
@Configuration
@ComponentScan({"com.atguigu"})
public class MainConfigAutowired {
}
測試類
public class TestAuto {
AnnotationConfigApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfigAutowired.class);
@Test
public void testAutowired(){
BookService bookService = applicationContext.getBean(BookService.class);
BookDAO bookDAO = applicationContext.getBean(BookDAO.class);
System.out.println(bookService);
System.out.println(bookDAO);
}
}
測試結(jié)果
com.atguigu.service.BookService@7357a011
com.atguigu.dao.BookDAO@30bce90b
25、@Qualifier&自動裝配
@Qualifier明確指定需要裝配哪一個組件,具體寫法如:@Qualifier(“bookDAO3”)
@Configuration
@ComponentScan({"com.atguigu"})
public class MainConfigAutowired {
@Qualifier("bookDAO")
@Bean("bookDAO2")
public BookDAO bookDAO(){
BookDAO bookDAO = new BookDAO();
bookDAO.setLable("2");
return bookDAO;
}
}
26、@Primary自動裝配
如果容器內(nèi)沒有任何bean,單IOC自動裝配默認(rèn)一定要將屬性裝配好,否則會報錯,可以使用在@Autowired(required=false),這里設(shè)置了required為非必須
以上情況可以使用@Primary來讓Spring裝配的時候,選擇該注解的類為首選類
@Configuration
@ComponentScan({"com.atguigu"})
public class MainConfigAutowired {
@Qualifier("bookDAO")
@Bean("bookDAO2")
public BookDAO bookDAO(){
BookDAO bookDAO = new BookDAO();
bookDAO.setLable("2");
return bookDAO;
}
}
27、@Resource自動裝配
@Resource是用來 替代@Autowired的,和@Autowired一樣實(shí)現(xiàn)自動裝配,默認(rèn)按照組件名稱進(jìn)行裝配,沒有能支持@Primary
@Service
public class BookService {
@Resource
private BookDAO bookDAO2;
public void print(){
System.out.println(bookDAO2);
}
}
28、@Inject自動裝配
- 也是用來替代@Autowired的
- 需要在pom.xml中導(dǎo)入inject依賴
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
裝配的寫法
@Service
public class BookService {
@Inject
private BookDAO bookDAO2;
public void print(){
System.out.println(bookDAO2);
}
}
29、標(biāo)注在方法上方法的自動裝配
默認(rèn)加在ioc容器的組件,容器啟動會調(diào)用無參構(gòu)造器創(chuàng)建對象,再進(jìn)行初始化等操作
- 標(biāo)注在方法上,Spring容器 創(chuàng)建當(dāng)前對象,就會調(diào)用方法,完成賦值, 方法使用的參數(shù),自定義類型的值從ioc容易中獲取
- 標(biāo)注在構(gòu)造方法上
- 也可以放在參數(shù)列表上
Boos類
@Component
public class Boss {
private Car car;
public Car getCar(){
return car;
}
//標(biāo)注在方法上,Spring容器 創(chuàng)建當(dāng)前對象,就會調(diào)用方法,完成賦值
//方法使用的參數(shù),自定義類型的值從ioc容易中獲取
@Autowired
public void setCar(Car car){
this.car=car;
}
@Override
public String toString() {
return "Boss{" +
"car=" + car +
'}';
}
}
Car類
@Component
public class Car {
}
測試 類
public class TestAuto {
@Test
public void testAutowired(){
AnnotationConfigApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfigAutowired.class);
Boss Boos = applicationContext.getBean(Boss.class);
System.out.println(Boos);
Car car = applicationContext.getBean(Car.class);
System.out.println(car);
}
}
測試結(jié)果
Boss{car=com.atguigu.bean.Car@198d6542}
com.atguigu.bean.Car@198d6542
ps:兩個car對象的地址是一樣的
- 如果只有一個有參構(gòu)造器,則參數(shù)上的@Autowired可以不寫,可以從組件中自動獲取
30、標(biāo)注在構(gòu)造器位置的自動裝配
- 也可以把@Autowried放在有參構(gòu)造器上
@Component
public class Boss {
private Car car;
@Autowired
public Boss(Car car) {
this.car = car;
}
public Car getCar(){
return car;
}
//標(biāo)注在方法上,Spring容器 創(chuàng)建當(dāng)前對象,就會調(diào)用方法,完成賦值
//方法使用的參數(shù),自定義類型的值從ioc容易中獲取
//@Autowired
public void setCar(Car car){
this.car=car;
}
@Override
public String toString() {
return "Boss{" +
"car=" + car +
'}';
}
}
- 還可以放在參數(shù)列表上
@Component
public class Boss {
private Car car;
public Boss(Car car) {
this.car = car;
}
public Car getCar(){
return car;
}
//標(biāo)注在方法上,Spring容器 創(chuàng)建當(dāng)前對象,就會調(diào)用方法,完成賦值
//方法使用的參數(shù),自定義類型的值從ioc容易中獲取
//@Autowired
public void setCar(@Autowired Car car){
this.car=car;
}
@Override
public String toString() {
return "Boss{" +
"car=" + car +
'}';
}
}
31、Aware注入Spring底層組件
自定義組件要想使用Spring容器底層的一些組件(ApplicationContext,BeanFactory等)
- 自定義組件實(shí)現(xiàn)XXXAware
- 在創(chuàng)建對象 的時候,會調(diào)用接口規(guī)定的方法注入相應(yīng)組件,
- Aware把Spring底層的一些組件注入到自定義的bean中
bean類
@Component
public class Red implements ApplicationContextAware, BeanNameAware, EmbeddedValueResolverAware {
private ApplicationContext applicationContext;
//獲得一個注解的環(huán)境
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
System.out.println(applicationContext);
}
//可以設(shè)置bean的名字
@Override
public void setBeanName(String name) {
System.out.println(name);
}
//傳入String值的解析器
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
String osName = stringValueResolver.resolveStringValue("你好${os.name}");
System.out.println(osName);
}
}
測試類
public class TestAuto {
@Test
public void testAutowired(){
AnnotationConfigApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfigAutowired.class);
}
}
測試結(jié)果
red
你好Mac OS X
org.springframework.context.annotation.AnnotationConfigApplicationContext@214b199c: startup date [Mon Jul 31 11:27:51 CST 2023]; root of context hierarchy
32、@Profile環(huán)境搭建
Profile是Spring為我們提供的可以根據(jù)當(dāng)前環(huán)境,動態(tài)的激活和切換一系列組件(bean)的功能。
環(huán)境:開發(fā)環(huán)境,測試環(huán)境,生產(chǎn)環(huán)境,在不同環(huán)境下可能鏈接不同的數(shù)據(jù)庫,因此需要可以根據(jù)當(dāng)前環(huán)境,動態(tài)的激活和切換一系列組件。
如引不同的數(shù)據(jù)源,需要導(dǎo)入以下依賴
c3p0和mysql鏈接驅(qū)動
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
創(chuàng)建dbConfig.propreties
db.user=root
db.password=xxxxxxxx
db.driverClass=com.mysql.cj.jdbc.Driver
創(chuàng)建配置類
@PropertySource("classpath:/dbConfig.properties")
@Configuration
public class MainConfigProfile implements EmbeddedValueResolverAware {
@Value("${db.user}")
private String user;
//值解析器
private StringValueResolver valueResolver;
private String driverClass;
@Bean("productDatasource")
public DataSource dataSource(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/fruitdb");
//使用值解析器解析driver
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Bean("testDatasource")
public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/empdb");
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Bean("developmentDatasource")
public DataSource dataSourceDevelopment(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/userDb");
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
this.valueResolver=stringValueResolver;
this.driverClass=this.valueResolver.resolveStringValue("${db.driverClass}");
}
}
測試類
public class TestAuto {
@Test
public void testAutowired(){
AnnotationConfigApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfigProfile.class);
//獲取beans的類名數(shù)組
String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
for (String name: beanNamesForType ) {
System.out.println(name);
}
}
}
測試結(jié)果
productDatasource
testDatasource
developmentDatasource
33、@Profile根據(jù)環(huán)境注冊bean
- @Profile:指定組件在哪個環(huán)境的情況下才能被注冊到容器中,不指定的話,在任何情況下都能注冊組件
- 加了環(huán)境標(biāo)識(@Profile)的bean,只有這個環(huán)境被激活才能注冊到容器中,默認(rèn)都default標(biāo)識被注冊
- 沒有標(biāo)注環(huán)境標(biāo)識的bean,在任何環(huán)境下都是加載的
@Profile("default")
如何激活
1)使用命令行動態(tài)參數(shù):在虛擬機(jī)參數(shù)位置加載-Dspring.profiles.active=test或其他標(biāo)識
2)代碼方式
配置類
@PropertySource("classpath:/dbConfig.properties")
@Configuration
public class MainConfigProfile implements EmbeddedValueResolverAware {
@Value("${db.user}")
private String user;
//值解析器
private StringValueResolver valueResolver;
private String driverClass;
@Profile("test")
@Bean
public Red red(){
return new Red();
}
//定義生產(chǎn)環(huán)境
@Profile("product")
@Bean("productDatasource")
public DataSource dataSource(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/fruitdb");
//使用值解析器解析driver
dataSource.setDriverClass(driverClass);
return dataSource;
}
//定義測試環(huán)境
@Profile("test")
@Bean("testDatasource")
public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/empdb");
dataSource.setDriverClass(driverClass);
return dataSource;
}
//定義開發(fā)環(huán)境
@Profile("development")
@Bean("developmentDatasource")
public DataSource dataSourceDevelopment(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost8080:3306/userDb");
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
this.valueResolver=stringValueResolver;
this.driverClass=this.valueResolver.resolveStringValue("${db.driverClass}");
}
}
測試類
public class TestAuto {
@Test
public void testAutowired(){
//1.獲取一個applicationContext
AnnotationConfigApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfigProfile.class);
//2.設(shè)置激活的環(huán)境
applicationContext.getEnvironment().setActiveProfiles("test","product");//設(shè)置了兩個環(huán)境
//3.注冊住配置類
applicationContext.register(MainConfigProfile.class);
//4.刷新容器
applicationContext.refresh();
//獲取beans的類名數(shù)組
String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
for (String name: beanNamesForType ) {
System.out.println(name);
}
}
}
測試結(jié)果
應(yīng)該出現(xiàn)test和product兩個組件,但在執(zhí)行refresh的時候報錯。GenericApplicationContext does not support multiple refresh attempts: just call ‘refresh’ once
3)不僅可以寫在bean上還可以寫在類上文章來源:http://www.zghlxwxcb.cn/news/detail-628840.html
@Profile("development")
@PropertySource("classpath:/dbConfig.properties")
@Configuration
public class MainConfigProfile implements EmbeddedValueResolverAware {
表示只有環(huán)境為development的時候,只有是指定的環(huán)境的時候,整個配置類里面的所有配置才生效文章來源地址http://www.zghlxwxcb.cn/news/detail-628840.html
到了這里,關(guān)于spring注解驅(qū)動開發(fā)(二)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!