Spring中為了減少XML配置,可以聲明一個配置類類對bean進行配置,主要用到兩個注解@Configuration和@bean
例子:
- 首先,XML中進行少量的配置來啟動java配置:
<?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/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <context:component-scan base-package="com.demo.config"/> </beans>
- 定義一個配置類,用@Configuration注解該類,等價於XML里的<beans>,用@Bean注解方法,等價於XML配置的<bean>,方法名等於beanId。代碼如下:
@Configuration public class SpringConfig { @Bean public Service service(){ return new Service(); } @Bean public Client client(){ return new Client(); } }
- 其他Bean代碼:
public class Service { public String sayHello(){ return "HelloWord!"; } }
public class Client { @Autowired Service service; public void invokeService(){ System.out.println("client invoke :" + service.sayHello()); } }
- 測試類
public class Test { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); Client client = context.getBean("client",Client.class); client.invokeService(); } }
加載XML中配置的beans和bean用:
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/bean.xml");// 讀取bean.xml中的內容
Counter c = ctx.getBean("client", Client.class);// 創建bean的引用對象
- 運行結果
- 寫在最后
SpringBean的創建和注入有三種,XML、注解、java配置文件。
因為XML配置較為繁瑣,現在大部分開始用注解和java配置,一般什么時候用注解或者java配置呢?
基本原則是:全局配置用java配置(如數據庫配置,MVC,redis等相關配置),業務Bean的配置用注解(@Service @Component@Repository@Controlle)。