Spring自动组装的方式设置bean之间的依赖关系

就是在beans标签里面加上一个default-autowire的属性取值有byType,byName,constructor,default,no常用就是byType和byName

1.根据类型自动组装。

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd"
default-autowire="byType">

<bean id="userdao" class="chp1.ex1.dao.UserDAO"></bean>
<bean id="userserv" class="chp1.ex1.service.UserService">	 
</bean>
</beans>

byType就是根据类型自动组装,在beans里设置了以后就不需要在bean标签里面设置property属性了,运行程序的时候Spring框架会根据Action里属性的类型自动创建一个该类型的对象,Service里的Dao对象也是如此创建。


2.根据名字自动组装

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd"
default-autowire="byName">

<bean id="userdao" class="chp1.ex1.dao.UserDAO"></bean>
<bean id="userserv" class="chp1.ex1.service.UserService">	 
</bean>
</beans>
byName就是根据名字自动组装,运行程序的时候Spring框架会根据Action里属性名去配置文件里找id为这个名的类,并创建该类的对象。

这里只介绍这两种常用的,虽然这两种比较常用,但是还是不推荐这样写,因为这样写,在配置文件里看不出各个类的依赖关系,可读性差。

猜你喜欢

转载自blog.csdn.net/Quan_qqqq/article/details/80397887