一、基于XML的方法
1.属性的注入
<bean id="car" class="com.baobaotao.ditype.Car"> <property name="brand" value="红旗&CA72"/> <property name="maxSpeed" value="200"/> <property name="price" value="20000.00"/> </bean> <bean id="boss" class="com.baobaotao.ditype.Boss"> <property name="car" ref="car"/> </bean>
也可以用简写的方式:
<bean id="car" class="com.baobaotao.ditype.Car" p:brand="红旗&CA72" p:maxSpeed="200" p:price="20000.00"/> <bean id="boss" class="com.baobaotao.ditype.Boss" p:car-ref="car"/>
有字面值属性:
<bean id="car" class="com.baobaotao.attr.Car" lazy-init="default"> <property name="brand"> <value> <![CDATA[红旗&CA72]]> </value> </property> <property name="maxSpeed"> <value>200</value> </property> <property name="price" value="2000.00" /> </bean>
2.构造函数注入
根据type
<bean id="car1" class="com.baobaotao.ditype.Car"> <constructor-arg type="java.lang.String"> <value>红旗CA72</value> </constructor-arg> <constructor-arg type="double"> <value>20000</value> </constructor-arg> </bean>
根据index
<bean id="car2" class="com.baobaotao.ditype.Car"> <constructor-arg index="0" value="红旗CA72" /> <constructor-arg index="1" value="中国一汽" /> <constructor-arg index="2" value="20000" /> </bean>
根据type和index
<bean id="car3" class="com.baobaotao.ditype.Car"> <constructor-arg index="0" type="java.lang.String"> <value>红旗CA72</value> </constructor-arg> <constructor-arg index="1" type="java.lang.String"> <value>中国一汽</value> </constructor-arg> <constructor-arg index="2" type="int"> <value>200</value> </constructor-arg> </bean>
3.工厂方法注入
<bean id="carFactory" class="com.baobaotao.ditype.CarFactory" /> <bean id="car5" factory-bean="carFactory" factory-method="createHongQiCar"> </bean>
4.内部Bean
<bean id="boss2" class="com.baobaotao.attr.Boss"> <property name="car"> <bean class="com.baobaotao.attr.Car"> <property name="maxSpeed" value="200" /> <property name="price" value="2000.00" /> </bean> </property> </bean>
5.继承类
<bean id="parentBoss" abstract="true" class="com.baobaotao.attr.Boss"> <property name="favorites"> <set> <value>看报</value> <value>赛车</value> <value>高尔夫</value> </set> </property> </bean> <bean id="childBoss" parent="parentBoss"> <property name="favorites"> <set merge="true"> <value>爬山</value> <value>游泳</value> </set> </property> </bean>
6.集合类
<bean id="boss1" class="com.baobaotao.attr.Boss"> <property name="car" ref="car" /> <property name="favorites1"> <set> <value>看报</value> <value>赛车</value> <value>高尔夫</value> </set> </property> <property name="favorites2"> <list> <value>看报</value> <value>赛车</value> <value>高尔夫</value> </list> </property> <property name="jobs"> <map> <entry > <key> <value>AM</value> </key> <value>会见客户</value> </entry> <entry> <key> <value>PM</value> </key> <value>公司内部会议</value> </entry> </map> </property> <property name="mails"> <props> <prop key="jobMail">john-office@baobaotao.com</prop> <prop key="lifeMail">john-life@baobaotao.com</prop> </props> </property> </bean>
7.FactoryBean
Java Bean
package com.baobaotao.fb;
import org.springframework.beans.factory.FactoryBean;
public class CarFactoryBean implements FactoryBean<Car> {
private String carInfo;
public String getCarInfo() {
return carInfo;
}
public void setCarInfo(String carInfo) {
this.carInfo = carInfo;
}
public Car getObject() throws Exception {
Car car = new Car();
String[] infos = carInfo.split(",");
car.setBrand(infos[0]);
car.setMaxSpeed(Integer.parseInt(infos[1]));
car.setPrice(Double.parseDouble(infos[2]));
return car;
}
public Class<Car> getObjectType() {
return Car.class;
}
public boolean isSingleton() {
return false;
}
}
XML
<bean id="car1" class="com.baobaotao.fb.CarFactoryBean" p:carInfo="红旗CA72,200,20000.00"/>
8.properties读取
<context:property-placeholder location="classpath:com/baobaotao/placeholder/jdbc.properties"/> <context:component-scan base-package="com.baobaotao.beanprop"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}" p:username="${userName}" p:password="${password}" />
二、基于注解的方法
java类使用下面的注解:
@Component
@Repository
@Service
@Controller
package com.baobaotao.anno;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Scope("session")
@Service
public class LogonService implements BeanNameAware{
@Autowired(required=false)
private LogDao logDao;
@Autowired
@Qualifier("userDao")
private UserDao userDao;
public LogDao getLogDao() {
return logDao;
}
public UserDao getUserDao() {
return userDao;
}
public void setBeanName(String beanName) {
System.out.println("beanName:"+beanName);
}
public void initMethod1(){
System.out.println("initMethod1");
}
public void initMethod2(){
System.out.println("initMethod2");
}
// @Autowired
// public void setLogDao(LogDao logDao) {
// this.logDao = logDao;
// }
//
// @Autowired
// @Qualifier("userDao")
// public void setUserDao(UserDao userDao) {
// System.out.println("auto inject");
// this.userDao = userDao;
// }
// @Autowired
// public void init(@Qualifier("userDao")UserDao userDao,LogDao logDao){
// System.out.println("multi param inject");
// this.userDao = userDao;
// this.logDao =logDao;
// }
}
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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" > <context:component-scan base-package="com.baobaotao.anno"/> <bean class="com.baobaotao.anno.LogonService"></bean> <!-- <context:component-scan base-package="com.baobaotao" resource-pattern="anno/*.class"/> <context:component-scan base-package="com.baobaotao"> <context:include-filter type="regex" expression="com\.baobaotao\.anno.*Dao"/> <context:include-filter type="regex" expression="com\.baobaotao\.anno.*Service"/> <context:exclude-filter type="aspectj" expression="com.baobaotao..*Controller+"/> </context:component-scan> <context:component-scan base-package="com.baobaotao"> <context:include-filter type="aspectj" expression="com.baobaotao.anno.*Plugin+"/> <context:include-filter type="aspectj" expression="com.baobaotao.anno.MyComponent"/> </context:component-scan> --> </beans>
三、基于java类的配置
Spring提供一个AnnotationConfigApplicationContext类,它能够直接通过标注@Configuration的Java类启动Spring容器:
Java Code:
package com.baobaotao.conf;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JavaConfigTest {
public static void main(String[] args) {
//1.通过构造函数加载配置类
// ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConf.class);
//2.通过编码方式注册配置类
// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// ctx.register(DaoConfig.class);
// ctx.register(ServiceConfig.class);
// ctx.refresh();
//3.通过XML组装@Configuration配置类所提供的配置信息
// ApplicationContext ctx = new ClassPathXmlApplicationContext("com/baobaotao/conf/beans2.xml");
//4.通过@Configuration组装XML配置所提供的配置信息
// ApplicationContext ctx = new AnnotationConfigApplicationContext(LogonAppConfig.class);
//5.@Configuration的配置类相互引用
ApplicationContext ctx = new AnnotationConfigApplicationContext(DaoConfig.class,ServiceConfig.class);
LogonService logonService = ctx.getBean(LogonService.class);
System.out.println((logonService.getLogDao() !=null));
logonService.printHelllo();
}
}
DaoConfig java code:
package com.baobaotao.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class DaoConfig {
@Bean(name="")
public UserDao userDao(){
return new UserDao();
}
@Scope("prototype")
@Bean
public LogDao logDao(){
return new LogDao();
}
}
ServiceConfig java code:
package com.baobaotao.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
@Configuration
@Import(DaoConfig.class)
public class ServiceConfig {
@Autowired
private DaoConfig daoConfig;
@Bean
public LogonService logonService(){
LogonService logonService = new LogonService();
System.out.println(daoConfig.logDao() == daoConfig.logDao());
logonService.setLogDao(daoConfig.logDao());
logonService.setUserDao(daoConfig.userDao());
return logonService;
}
}
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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.baobaotao.conf" resource-pattern="AppConf.class" /> </beans>
四、三种方式的比较
XML | 注解 | Java类 | |
适合场景 | 1.Bean实现类来源于第三方类库,如Datasource、JdbcTemplete、HibernateTemplate等; 2.命名空间的配置,如aop、context等 | Bean的实现类是当前项目开发的,可以直接在Java类中使用基于注解的配置,如DAO,Service,Controller类 | 通过代码的方式控制Bean初始化的整体 ,实例化Bean的逻辑比较复杂的情况 |