【SpringBoot】使用Java配置方式

00潤物無聲00發表於2017-08-08

Java配置是Spring4.x推薦的配置方式,完全替代xml配置


@Configuration 和 @Bean
Spring的Java配置方式是通過 @Configuration 和 @Bean 這兩個註解實現的:
1、@Configuration 作用於類上,相當於一個xml配置檔案;
2、@Bean 作用於方法上,相當於xml配置中的<bean>;


建立maven專案,匯入依賴

<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.dynamic.springconfig</groupId>
  <artifactId>dynamic-springconfig</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>dynamic-springconfig</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.3.7.RELEASE</version>
    </dependency>
    
    <!-- 連線池 -->
    <dependency>
    	<groupId>com.jolbox</groupId>
    	<artifactId>bonecp-spring</artifactId>
    	<version>0.8.0.RELEASE</version>
    </dependency>

  </dependencies>
  
  <build>
  	<finalName>${project.artifactId}</finalName>
  	<plugins>
  		<!-- 資原始檔拷貝外掛 -->
  		<plugin>
  			<groupId>org.apache.maven.plugins</groupId>
  			<artifactId>maven-resources-plugin</artifactId>
  			<configuration>
  				<encoding>UTF-8</encoding>
  			</configuration>
  		</plugin>
  		
  		<!-- Java編譯外掛 -->
  		<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>
  		<!-- 配置Tomcat外掛 -->
  		<plugin>
  			<groupId>org.apache.tomcat.maven</groupId>
  			<artifactId>tomcat7-maven-plugin</artifactId>
  			<version>2.2</version>
  		</plugin>
  		<!--  新增配置,放過該錯誤提示。web.xml is missing and <failOnMissingWebXml> is set to true-->
  		 <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-war-plugin</artifactId>  
            <version>2.2</version>  
            <configuration>  
                <failOnMissingWebXml>false</failOnMissingWebXml>  
            </configuration>  
        </plugin> 
  		</plugins>
  	</pluginManagement>
  </build>
  
</project>


一.使用Java配置方式

User實體

package com.dynamic.springconfig;
public class User {
	   private String username;
	    private String password;
	    private Integer age;
}

UserDao

package com.dynamic.springconfig;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
	public List<User> queryUserList()
	{
		List<User> result = new ArrayList<User>();
		//模擬資料庫的查詢
		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;
	}
}

UserService

package com.dynamic.springconfig;
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();
	}

}

啟動類

package com.dynamic.springconfig;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * Hello world!
 */
@Configuration//通過該註解來表明該類是一個Spring的配置,相當於一個xml檔案
@ComponentScan(basePackages="com.dynamic.springconfig")//掃描包
@PropertySource(value= {"classpath:test.properties"},ignoreResourceNotFound = false)
public class App 
{	
	@Value("${test}")
	private String test;
	@Bean //通過該註解來表明是一個Bean物件,相當於xml中的<bean>
	public  UserDao getUserDao()
	{
		System.out.println(test);
		return new UserDao();
	}
    public static void main( String[] args )
    { 	
    	//通過Java配置來例項化Spring容器
    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);	
    	//在Spring容器中獲取Bean物件
    	UserService userService = context.getBean(UserService.class);
    	//呼叫物件中的方法
    	List<User> List = userService.queryUserList();
    	for(User user:List)
    	{
    		System.out.println(user.getUsername() + ","+ user.getAge());
    	}
    	
    	
     	
    }
}


啟動類中可以看到它宣告為配置類,配置了包掃描,讀取屬性檔案。

test.properties

test=success


對比使用xml配置。在原始碼的基礎上,我們加入配置檔案。

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:component-scan base-package="com.dynamic.springconfig">
	</context:component-scan>
	
	<context:property-placeholder location="test.properties"/>
	<bean id="userDao" class="com.dynamic.springconfig.UserDao"></bean>

</beans>

啟動類

package com.dynamic.springxml;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dynamic.springconfig.User;
import com.dynamic.springconfig.UserService;

public class AppXml {

	@Value("${test}")
	private String test;
	
	public static void main(String[] args)
	{
		ApplicationContext context = new  ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = (UserService) context.getBean("userService");
		List<User> list =userService.queryUserList(); 
		for(User user:list)
    	{
    		System.out.println(user.getUsername() + ","+ user.getAge());
    	}		
	}
}

  使用Java配置替換XML配置



相關文章