自动装配:
根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类
型属性赋值
①场景模拟
创建类
UserController
-
public
class
UserController {
-
-
private UserService userService;
-
public
void
setUserService
(UserService userService) {
-
this.userService = userService;
-
}
-
public
void
saveUser
(){
-
userService.saveUser();
-
}
-
}
创建接口
UserService
-
public
interface
UserService {
-
void
saveUser
();
-
}
创建类
UserServiceImpl
实现接口
UserService
-
public
class
UserServiceImpl
implements
UserService {
-
private UserDao userDao;
-
-
public
void
setUserDao
(UserDao userDao) {
-
this.userDao = userDao;
-
}
-
-
@Override
-
public
void
saveUser
(){
-
userDao.saveUser();
-
}
-
-
}
创建接口
UserDao
-
public
interface
UserDao {
-
void
saveUser
();
-
}
创建类
UserDaoImpl
实现接口
UserDao
-
public
class
UserDaoImpl
implements
UserDao {
-
@Override
-
public
void
saveUser
() {
-
System.out.println(
"保存成功");
-
}
-
}
②配置
bean
-
<bean id=
"userController" class=
"com.atguigu.spring.Controller.UserController">
-
<property name=
"userService" ref=
"userService"></property>
-
</bean>
-
<bean id=
"userService" class=
"com.atguigu.spring.Service.impl.UserServiceImpl">
-
<property name=
"userDao" ref=
"userDao"></property>
-
</bean>
-
<bean id=
"userDao" class=
"com.atguigu.spring.Dao.impl.UserDaoImpl"></bean>
③测试
-
@Test
-
public
void
test2
(){
-
ConfigurableApplicationContext
ioc
=
new
ClassPathXmlApplicationContext(
"spring-autowire-xml.xml");
-
UserController
userController
= ioc.getBean(
"userController", UserController.class);
-
userController.saveUser();
-
}
④使用bean标签的autowire属性设置自动装配效果
自动装配方式:byType
byType
:根据类型匹配
IOC
容器中的某个兼容类型的
bean
,为属性自动赋值
- 若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值 null
- 若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常 NoUniqueBeanDefinitionException
-
<bean id=
"userController" class=
"com.atguigu.spring.Controller.UserController" autowire=
"byType">
-
<!-- <property name=
"userService" ref=
"userService"></property>-->
-
</bean>
-
<bean id=
"userService" class=
"com.atguigu.spring.Service.impl.UserServiceImpl" autowire=
"byType">
-
<!-- <property name=
"userDao" ref=
"userDao"></property>-->
-
</bean>
-
<bean id=
"userDao" class=
"com.atguigu.spring.Dao.impl.UserDaoImpl"></bean>
⑤测试
自动装配方式:byName
byName
:将自动装配的属性的属性名,作为
bean
的
id
在
IOC
容器中匹配相对应的
bean
进行赋值
-
<bean id=
"userController" class=
"com.atguigu.spring.Controller.UserController" autowire=
"byName">
-
<!-- <property name=
"userService" ref=
"userService"></property>-->
-
</bean>
-
<bean id=
"userService" class=
"com.atguigu.spring.Service.impl.UserServiceImpl" autowire=
"byName">
-
<!-- <property name=
"userDao" ref=
"userDao"></property>-->
-
</bean>
-
<bean id=
"userDao" class=
"com.atguigu.spring.Dao.impl.UserDaoImpl"></bean>
转载:https://blog.csdn.net/Javascript_tsj/article/details/128186976
查看评论