4、Spring注解开发,第四天

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/LeeDemoOne/article/details/102745758

第四天:Spring annotation开发

目录:1、bean的生命周期-初始化和销毁方法 2、@Value赋值 3、@PropertySource加载外部配置文件 4、@Profile根据外部环境注册

一、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);
        }
    }

结果:

-->dataSourceTest

猜你喜欢

转载自blog.csdn.net/LeeDemoOne/article/details/102745758