国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

spring注解驅(qū)動開發(fā)(二)

這篇具有很好參考價值的文章主要介紹了spring注解驅(qū)動開發(fā)(二)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

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上還可以寫在類上

@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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Java企業(yè)級開發(fā)學(xué)習(xí)筆記(4.4)Spring Boot加載自定義配置文件

    Java企業(yè)級開發(fā)學(xué)習(xí)筆記(4.4)Spring Boot加載自定義配置文件

    創(chuàng)建 Spring Boot 項(xiàng)目 單擊【創(chuàng)建】按鈕 在 resources 里創(chuàng)建 myconfig.properties 文件 設(shè)置文件編碼 設(shè)置學(xué)生的四個屬性值 在 cn.kox.boot 包里創(chuàng)建config子包,在子包里創(chuàng)建 StudentConfig 打開自帶的測試類 ConfigDemo01ApplicationTests 注入學(xué)生配置實(shí)體,創(chuàng)建 testStudentConfig() 測試方法,在里面輸

    2024年02月08日
    瀏覽(27)
  • JAVA后端開發(fā)面試基礎(chǔ)知識(八)——Spring

    JAVA后端開發(fā)面試基礎(chǔ)知識(八)——Spring

    Spring是一個輕量級Java開發(fā)框架 我們一般說 Spring 框架指的都是 Spring Framework,它是很多模塊的集合,使用這些模塊可以很方便地協(xié)助我們進(jìn)行開發(fā),比如說 Spring 支持 IoC(Inverse of Control:控制反轉(zhuǎn)) 和 AOP(Aspect-Oriented Programming:面向切面編程)、可以很方便地對數(shù)據(jù)庫進(jìn)行訪問、

    2024年03月10日
    瀏覽(25)
  • Spring-2-深入理解Spring 注解依賴注入(DI):簡化Java應(yīng)用程序開發(fā)

    Spring-2-深入理解Spring 注解依賴注入(DI):簡化Java應(yīng)用程序開發(fā)

    ? 掌握純注解開發(fā)依賴注入(DI)模式 學(xué)習(xí)使用純注解進(jìn)行第三方Bean注入 問題導(dǎo)入 思考:如何使用注解方式將Bean對象注入到類中 1.1 使用@Autowired注解開啟自動裝配模式(按類型) 說明:不管是使用配置文件還是配置類,都必須進(jìn)行對應(yīng)的Spring注解包掃描才可以使用。@Autowired默

    2024年02月14日
    瀏覽(32)
  • Spring注解驅(qū)動開發(fā)(二)

    Spring注解驅(qū)動開發(fā)(二)

    注:此筆記為尚硅谷Spring注解驅(qū)動教程(雷豐陽源碼級講解)學(xué)習(xí)筆記,并同時參考[https://blog.csdn.net/xjhqre/article/details/123264069]博主文章,其中包含個人的筆記和理解,僅做學(xué)習(xí)筆記之用。 簡述: 1、實(shí)例化一個Bean--也就是我們常說的new; 2、按照Spring上下文對實(shí)例化的Bean進(jìn)

    2024年02月03日
    瀏覽(21)
  • spring注解驅(qū)動開發(fā)(二)

    17、Bean的生命周期 bean的生命周期:bean的創(chuàng)建—初始化—銷毀的過程 容器負(fù)責(zé)管理bean的生命周期 我們可以自定義初始化和銷毀方法,容器在bean進(jìn)行到當(dāng)前生命周期的時候來調(diào)用我們自定義的初始化和銷毀方法 構(gòu)造(對象創(chuàng)建) 單實(shí)例:在容器啟動時創(chuàng)建對象 多實(shí)例:在每

    2024年02月14日
    瀏覽(20)
  • spring注解驅(qū)動開發(fā)(一)

    Spring常用注解(絕對經(jīng)典) 1、需要導(dǎo)入的spring框架的依賴 2、@Configuration 設(shè)置類為配置類 3、AnnotationConfigApplicationContext 通過配置類獲取上下文環(huán)境applicationContext 可以通過getBeanDefinitionNames()獲得配置類中配置的各類Bean 也可以使用getBeanNamesForType()通過類型來獲得bean的name(id)

    2024年02月14日
    瀏覽(20)
  • Java SE 學(xué)習(xí)筆記(十八)—— 注解、動態(tài)代理

    Java SE 學(xué)習(xí)筆記(十八)—— 注解、動態(tài)代理

    Java 注解(Annotation)又稱Java標(biāo)注,是JDK 5.0引入的一種注釋機(jī)制,Java語言中的類、構(gòu)造器、方法、成員變量、參數(shù)等都可以被注解進(jìn)行標(biāo)注,至于到底做何種處理由業(yè)務(wù)需求來決定。 例如: JUnit 框架中,標(biāo)記了注解 @Test 的方法就可以被當(dāng)成測試方法執(zhí)行,而沒有標(biāo)記的就不

    2024年02月08日
    瀏覽(21)
  • Java企業(yè)級信息系統(tǒng)開發(fā)學(xué)習(xí)筆記(4.2)Spring Boot項(xiàng)目單元測試、熱部署與原理分析

    Java企業(yè)級信息系統(tǒng)開發(fā)學(xué)習(xí)筆記(4.2)Spring Boot項(xiàng)目單元測試、熱部署與原理分析

    該文章主要為完成實(shí)訓(xùn)任務(wù),詳細(xì)實(shí)現(xiàn)過程及結(jié)果見【http://t.csdn.cn/pG623】 1. 添加測試依賴啟動器和單元測試 修改pom.xml文件,添加依賴 刷新項(xiàng)目依賴 2. 創(chuàng)建測試類與測試方法 在 src/test/java 里創(chuàng)建 cn.kox.boot 包,創(chuàng)建測試類 TestHelloWorld01 給測試類添加測試啟動器注解與Spring

    2024年02月10日
    瀏覽(27)
  • spring注解驅(qū)動開發(fā)(BEAN注冊方式與生命周期)

    spring注解驅(qū)動開發(fā)(BEAN注冊方式與生命周期)

    目錄 容器中注冊BEAN的方式 BEAN生命周期 包掃描+組件標(biāo)注注解 @ComponentScan(basePackages = {\\\"com.an.spring.condition\\\"}) @Service @Component @Controller @Repository @BEan方式【導(dǎo)入第三方包里面的組件】 @Import快速給容器中導(dǎo)入一個組件。 1)、@IMport(要導(dǎo)入到容器中的組件),容器就會注入這個組

    2024年02月07日
    瀏覽(48)
  • Spring注解驅(qū)動開發(fā)之常用注解案例_告別在XML中配置Bean

    注解驅(qū)動開發(fā)就是不再使用Spring的bean.xml文件,改為純使用注解的方式開發(fā) @Configuration 此注解為配置類注解,相當(dāng)于spring.xml文件,即配置類==配置文件 @Bean 給容器中注冊一個Bean;類型為返回值的類型,id默認(rèn)是用方法名作為id 示例 Person類(后續(xù)注解配置類中都會以此類舉例),

    2024年01月21日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包