1. 程式人生 > >4、Spring註解開發,第四天

4、Spring註解開發,第四天

一、bean的生命週期-初始化和銷燬方法

構造(物件建立)
	單例項:在容器啟動的時候建立物件
	多例項:在每次獲取的時候建立物件
初始化:
	物件建立完成,病賦值好,呼叫初始化方法	init-method PostConstruct
銷燬:
	單例項:容器關閉的時候
	多例項:容器不會管理這個bean,容器不會呼叫銷燬方法 destroy-method preDestroy

方式:
	1、@Bean(initMethod="xxx",destroyMethod="yyy")
	2、通過bean implements InitialzingBean(定義初始化邏輯)
	   通過bean implements DisposableBean(定義銷燬邏輯)
	3、@PostConstruct  @PreDestroy
	4、BeanPostProcessor[interface]:bean的後置處理器-----[針對容器中的所有bean]
		在bean初始化前後進行一些處理工作:
			postProcessBeforeInitialization(..)初始化之前處理
			postProcessAfterInitialization(..)初始化之後處理
		

二、@Value賦值

Person.java

package com.lee.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

@Data//生成GET SET方法
@NoArgsConstructor//無參建構函式
@AllArgsConstructor//有參建構函式
public class Person {

    //使用@Value賦值
    //1、基本數值 123
    //2、可以寫SPEL #{20-2}
    //3、可以寫${},去除配置檔案中的值(在執行環境變數裡面的值)
    @Value("1")
    private Integer id;

    @Value("#{20-2}")
    private Integer age;

    @Value("lee")
    private String username;

    @Value("male")
    private String gender;

}

MainConfig3.java

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MainConfig3 {

    @Bean
    public Person person(){
        return new Person();
    }

}

MainTest.java

  @Test
    public void testValue(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for(String name: names){
            System.out.println("-->"+name);
        }

        Person person = (Person) context.getBean("person");
        System.out.println(person);
    }

結果:

-->mainConfig3
-->person
Person(id=1, age=18, username=lee, gender=male)

三、@PropertySource載入外部配置檔案

Person.java

package com.lee.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;

@Data//生成GET SET方法
@NoArgsConstructor//無參建構函式
@AllArgsConstructor//有參建構函式
public class Person {

    //使用@Value賦值
    //1、基本數值 123
    //2、可以寫SPEL #{20-2}
    //3、可以寫${},去除配置檔案中的值(在執行環境變數裡面的值)
    @Value("1")
    private Integer id;

    @Value("#{20-2}")
    private Integer age;

    @Value("${person.username}")
    private String username;

    @Value("male")
    private String gender;

}

person.properties

person.username=李四
os.my.name=linux

MainConfig3.java

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

//@PropertySource讀取外部配置檔案中的K/V儲存到執行的環境變數中,
//載入完外部的配置檔案以後使用${}取出配置檔案中的值
//也可以用@PropertySources()來載入多個propertySource
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfig3 {

    @Bean
    public Person person(){
        return new Person();
    }

}

MainTest.java

    @Test
    public void testValue(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for(String name: names){
            System.out.println("-->"+name);
        }

        Person person = (Person) context.getBean("person");
        System.out.println(person);

        ConfigurableEnvironment environment = context.getEnvironment();
        String property = environment.getProperty("os.my.name");
        System.out.println(property);
    }

結果:

-->mainConfig3
-->person
Person(id=1, age=18, username=李四, gender=male)
linux

四、@Profile根據環境註冊

POM.XML

<!--c3p0-->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

MainConfig_profile.java

package com.lee.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
public class MainConfig_profile {

    @Profile("test")
    @Bean
    public DataSource dataSourceTest() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("admin123");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/sys");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Profile("dev")
    @Bean
    public DataSource dataSourceDev() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("admin123");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/sys");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Profile("prod")
    @Bean
    public DataSource dataSourceProd() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("admin123");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/sys");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        return dataSource;
    }


}

MainTest.java

 @Test
    public void testProfile_02(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().addActiveProfile("test");
        context.register(MainConfig_profile.class);
        context.refresh();
        String[] names = context.getBeanNamesForType(DataSource.class);
        for (String name : names){
            System.out.println("-->"+name);
        }
    }

    //VM OPTION 設定 -Dspring.profiles.active=test
    @Test
    public void testProfile_01(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig_profile.class);
        String[] names = context.getBeanNamesForType(DataSource.class);
        for (String name : names){
            System.out.println("-->"+name);
        }
    }

結果:

-->dat