Spring's java configuration

Spring's java configuration

1. Spring's java configuration

Java configuration is recommended by Spring 4. X and can completely replace xml configuration.

1.1 Use @Configuration and @Bean

Spring's Java configuration is implemented through @Configuration and @Bean annotations:

1. @Configuration acts on classes, which is equivalent to an xml configuration file.
2. @Bean acts on the method, which is equivalent to <bean> in xml configuration.

Example: Demonstrates how to configure Spring through Java configuration, and implements Spring IOC function.

(1) Create projects and import dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hcx.springboot</groupId>
  <artifactId>hcx-springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- Connection pool -->
        <dependency>
            <groupId>com.jolbox</groupId>
            <artifactId>bonecp-spring</artifactId>
            <version>0.8.0.RELEASE</version>
        </dependency>
</dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- Resource File Copy Plug-in -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- java Compiler plug-in -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!-- To configure Tomcat Plug-in unit -->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
  </build>
</project>

(2) Writing User Objects

package com.hcx.springboot.javaconfig;

public class User {
    
    private String username;
    private String password;
    private Integer age;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

}

(3) Write userdao to simulate the interaction with database

package com.hcx.springboot.javaconfig;

import java.util.ArrayList;
import java.util.List;

public class UserDao {
    
    public List<User> queryUserList(){
        List<User> result = new ArrayList<User>();
        //Query of Analog Database
        for(int i = 0;i<10;i++){
            User user = new User();
            user.setUsername("username_"+i);
            user.setPassword("password_"+i);
            user.setAge(i+1);
            result.add(user);
        }
        return result;
        
    }

}

(4) Write UserService to implement User data operation business logic

package com.hcx.springboot.javaconfig;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired        
    private UserDao userDao;
    
    public List<User> queryUserList(){
        return this.userDao.queryUserList();
    }
    
}

(5) Write Spring Config to instantiate Spring containers

package com.hcx.springboot.javaconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration//Annotations indicate that this class is a Spring configuration, equivalent to an xml file
@ComponentScan(basePackages="com.hcx.springboot.javaconfig")//Configure Scan Pack
public class SpringConfig {
    
    @Bean //This annotation indicates that it is a bean object, which is equivalent to < bean > in xml.
    public UserDao getUserDao(){
        return new UserDao(); 
    }

}

(6) Write test methods to start spring containers

package com.hcx.springboot.javaconfig;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    
    public static void main(String[] args) {
        //Instantiate spring container through java configuration
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        
        //Get the bean object in the spring container (because the com.hcx.springboot.javaconfig package has been scanned in context)
        UserService userService = context.getBean(UserService.class);
        
        //Calling methods in objects
        List<User> list = userService.queryUserList();
        for (User user : list) {
            System.out.println(user.getUsername() + ","+user.getPassword()+","+user.getPassword());
        }
        
        //Destruction container
        context.destroy();
    }

}

Operation results:

username_0,password_0,password_0
username_1,password_1,password_1
username_2,password_2,password_2
username_3,password_3,password_3
username_4,password_4,password_4
username_5,password_5,password_5
username_6,password_6,password_6
username_7,password_7,password_7
username_8,password_8,password_8
username_9,password_9,password_9

1.2 Read external resource profiles

The read configuration file can be specified by @PropertySource, and the value can be obtained by @Value annotation.

package com.hcx.springboot.javaconfig;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration//Annotations indicate that this class is a Spring configuration, equivalent to an xml file
@ComponentScan(basePackages="com.hcx.springboot.javaconfig")//Configure Scan Pack
@PropertySource(value={"classpath:jdbc.properties","xxx"},ignoreResourceNotFound=true)
public class SpringConfig {
    
    @Value("${jdbc.url}")
    private String jdbcUrl;
    
    @Bean //This annotation indicates that it is a bean object, which is equivalent to < bean > in xml.
    public UserDao getUserDao(){
        return new UserDao(); 
    }

}

Be careful:

1. Configure multiple configuration files: use, separate @PropertySource(value={"classpath:jdbc.properties","xxx"}
2. Configuration file does not exist: Ignore ResourceNotFound = true ignores

1.3 Configuration of database connection pool

The original XML-based configuration is written in the Spring configuration file applicationContext.xml:

<! - Define data sources - >
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
    destroy-method="close">
    <! - Database Driver - >
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <! - jdbcUrl - > corresponding driver
    <property name="jdbcUrl" value="${jdbc.url}" />
    <! - User name of database - >
    <property name="username" value="${jdbc.username}" />
    <! - The password of the database - >
    <property name="password" value="${jdbc.password}" />
    <! - Check the interval between idle connections in the database connection pool in divisions, defau lt value: 240, set to 0 - > if cancelled.
    <property name="idleConnectionTestPeriod" value="60" />
    <! - Maximum lifetime of unused links in connection pool, divided in units, defau lt value: 60, set to 0 - > if you want to survive forever.
    <property name="idleMaxAge" value="30" />
    <! - Maximum number of connections per partition - >
    <!-- 
        Judgment basis: number of concurrent requests
     -->
    <property name="maxConnectionsPerPartition" value="100" />
    <! - The smallest number of connections per partition - >
    <property name="minConnectionsPerPartition" value="5" />
</bean>

(1)jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hcx_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.username=root
jdbc.password=root

(2)SpringConfig:

package com.hcx.springboot.javaconfig;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.jolbox.bonecp.BoneCPDataSource;

@Configuration//Annotations indicate that this class is a Spring configuration, equivalent to an xml file
@ComponentScan(basePackages="com.hcx.springboot.javaconfig")//Configure Scan Pack
@PropertySource(value={"classpath:jdbc.properties"},ignoreResourceNotFound=true)
public class SpringConfig {
    
    @Bean //This annotation indicates that it is a bean object, which is equivalent to < bean > in xml.
    public UserDao getUserDao(){
        return new UserDao(); 
    }
    
    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.driverClassName}")
    private String jdbcDriverClassName;

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

    @Value("${jdbc.password}")
    private String jdbcPassword;

    /**
     * The method name is not appropriate if it is written as getBoneCPDataSource, because the default method name is the id of the bean.
     * @return
     */
    @Bean(destroyMethod = "close")
    public BoneCPDataSource boneCPDataSource(){ 
        BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
        
         // Database Driver
        boneCPDataSource.setDriverClass(jdbcDriverClassName);
        // Corresponding driven jdbcUrl
        boneCPDataSource.setJdbcUrl(jdbcUrl);
        // User name of database
        boneCPDataSource.setUsername(jdbcUsername);
        // Password of database
        boneCPDataSource.setPassword(jdbcUsername);
        // Check the interval between idle connections in the database connection pool, divided in units, default value: 240, set to 0 if cancelled
        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);
        // Maximum lifetime of unused links in connection pool is set to 0 in divisions, default value: 60, if you want to survive forever.
        boneCPDataSource.setIdleMaxAgeInMinutes(30);
        // Maximum number of connections per partition
        boneCPDataSource.setMaxConnectionsPerPartition(100);
        // Minimum number of connections per partition    
        boneCPDataSource.setMinConnectionsPerPartition(5);

        return boneCPDataSource;
    }

}

Use the DataSource object to reference or inject as before.

Keywords: JDBC Spring SpringBoot Java

Added by katierosy on Wed, 05 Jun 2019 00:14:22 +0300