並不是所有的人都喜歡用xml來配置spring,尤其是那些沒學過xml或者討厭xml的人。因此spring出現了一種基於java(就是通過寫java代碼來配置)的配置方法。
我在上次說過,springIOC容器,就是一個鍵值對的map,而且spring本來就是用java寫的,因此用java來進配置,就是相當於新建一個實例放入這個springIOC容器當中,這和我們平常寫代碼非常相似。
言歸正傳,使用java風格的第一步就是配置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.xsd
">
<!--這個liu就是你使用spring的包名-->
<context:component-scan base-package="liu"/>
</beans>
然後定義一個配置類:
比如在我的工程下有一個A類,我需要對A類進行注入,那麼在配置類中就可以這樣寫。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig{
@Bean
public A a(){
return new A();
}
}
@Configuration:這個註釋必須有,在spring掃描包的時候,掃描到這個註解就會把這個類當成配置類。也就相當於配置文件當中的一樣
@Bean:注入一個bean,也就是相當於配置文件當中的一樣
A:放回類型對應着中的class
a方法名:對應着中的id
有的人說這樣弄比配置有什麼優勢?
優勢在於注入值的時候。
比如A是這樣的
public class A{
private int num;
public A(int num){
this.num=num;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig{
@Bean
public A a(){
return new A(10);
}
}
你可以寫成上面這樣。
當然也可以是set注入:
public class A{
private int num;
public void setNum(int num){
this.num=num;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig{
@Bean
public A a(){
A aa=new A();
aa.setNum(10);
return aa;
}
}
還有通過引用來進行注入
public class A{
private B b;
public void setB(B b){
this.b=b;
}
}
public class B{
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig{
@Bean
public B b(){
return new B();
}
@Bean
public A a(){
A aa=new A();
aa.setB(b());
return aa;
}
}
剩下的大家舉一反三,比起配置文件方便了很多吧,尤其是注入複雜的參數的時候。