使用Spring的JavaConfig
2012-12-27 09:16 Rollen Holt 阅读(8742) 评论(1) 收藏 举报之前我们都是在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");
}
}
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================
浙公网安备 33010602011771号