使用Spring的JavaConfig


之前我們都是在xml文件中定義bean的,比如:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
	<bean id="helloBean" class="com.mkyong.hello.impl.HelloWorldImpl">
 
</beans>

其實我們可以使用注解來完成這些事情,例如下面的代碼,完成的功能和上面的xml配置的功能是一樣的:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;
 
@Configuration
public class AppConfig {
 
    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
 
}

 想象一個場景,我們有一個很大的工程項目,如果將所有的bean都配置在一個xml文件中,那么這個文件就會非常的大。所以在很多的時候我們都會將一個大的xml配置文件分割為好幾份。這樣方便管理,最后在總的那個xml文件中導入就行了,比如:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<import resource="config/customer.xml"/>
        <import resource="config/scheduler.xml"/>
 
</beans>

 但是現在我們也可以使用JavaConfig來完成同樣的工作了:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
 
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
 
}

  我們對這個例子來看一個demo:

CustomerBo.java

public class CustomerBo {
 
	public void printMsg(String msg) {
 
		System.out.println("CustomerBo : " + msg);
	}
 
}

 SchedulerBo.java

public class SchedulerBo {
 
	public void printMsg(String msg) {
 
		System.out.println("SchedulerBo : " + msg);
	}
 
}

  現在我們來使用注解:

@Configuration
public class CustomerConfig {
 
	@Bean(name="customer")
	public CustomerBo customerBo(){
 
		return new CustomerBo();
 
	}
}

  

@Configuration
public class SchedulerConfig {
 
	@Bean(name="scheduler")
	public SchedulerBo suchedulerBo(){
 
		return new SchedulerBo();
 
	}
 
}

  AppConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
 
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
 
}

  然后運行:

public class App {
	public static void main(String[] args) {
 
		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppConfig.class);
 
		CustomerBo customer = (CustomerBo) context.getBean("customer");
		customer.printMsg("Hello 1");
 
		SchedulerBo scheduler = (SchedulerBo) context.getBean("scheduler");
		scheduler.printMsg("Hello 2");
 
	}
}

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM