4. Spring Annotation Development, Day 4

Day 4: Spring annotation development

Directory: 1. bean Life Cycle - Initialization and Destruction Method 2, @Value Assignment 3, @PropertySource Loading External Configuration File 4, @Profile Registering According to External Environment

I. Life Cycle of Beans - Initialization and Destruction Methods

Construction (object creation)
	Single instance: Create objects at container startup
	Multi-instance: Create objects at each acquisition
 Initialization:
	Object creation completed, disease assignment is good, call initialization method init-method PostConstruct
 Destruction:
	Single instance: when container closes
	Multiple instances: The container does not manage the bean, and the container does not call destroy-method preDestroy

Method:
	1,@Bean(initMethod="xxx",destroyMethod="yyy")
	2. Define initialization logic by bean implements InitialzingBean
	   By bean implements Disposable Bean (Defining Destruction Logic)
	3,@PostConstruct  @PreDestroy
	4. BeanPostProcessor [interface]: Post Processor for beans - [for all beans in the container]
		Do some processing before and after bean initialization:
			Post ProcessBeforeInitialization (..) Pre-initialization Processing
			postProcessAfterInitialization(()) after initialization.
		

Value assignment

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 Generation Method
@NoArgsConstructor//non-parameter constructor
@AllArgsConstructor//Parametric constructor
public class Person {

    //Assignment with @Value
    //1. Basic value 123
    //2. Write SPEL#{20-2}
    //3. You can write ${} to remove the values in the configuration file (in the running environment variables)
    @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);
    }

Result:

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

3. @PropertySource loads external configuration files

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 Generation Method
@NoArgsConstructor//non-parameter constructor
@AllArgsConstructor//Parametric constructor
public class Person {

    //Assignment with @Value
    //1. Basic value 123
    //2. Write SPEL#{20-2}
    //3. You can write ${} to remove the values in the configuration file (in the running environment variables)
    @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=Li Si
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 reads the K/V in the external configuration file and saves it to the running environment variable.
//After loading the external configuration file, use ${} to fetch the value in the configuration file
//You can also use @PropertySources() to load multiple properties Sources
@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);
    }

Result:

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

4. @Profile registered according to the environment

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 Settings - 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);
        }
    }

Result:

-->dataSourceTest

Tags: Programming Java MySQL Lombok JDBC

Posted on Fri, 04 Oct 2019 13:00:59 -0400 by ricky spires