首页 > 代码库 > spring自动装配
spring自动装配
1.
自动装配: byName或byType
2. spring.xml中设置全局是byName自动装配
<?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:p="http://www.springframework.org/schema/p"
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" default-autowire="byName">
<!-- ###############自动装配############### -->
<bean id="userDao" class="cn.itcast.d_auto.UserDao"></bean>
<bean id="userService" class="cn.itcast.d_auto.UserService"></bean>
<!-- 如果根据类型自动装配: 必须确保IOC容器中只有一个该类型的对象 -->
<bean id="userAction" class="cn.itcast.d_auto.UserAction"></bean>
<!-- 报错: 因为上面已经有一个该类型的对象,且使用了根据类型自动装配
<bean id="userService_test" class="cn.itcast.d_auto.UserService" autowire="byType"></bean>
-->
</beans>
3.测试类
public class App { // 创建容器对象 private ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/d_auto/bean.xml"); @Test public void testExecuteAction() { // 从容器中获取Action UserAction userAction = (UserAction) ac.getBean("userAction"); userAction.execute(); } }
4. 控制层
public class UserAction { private UserService userService; public void setUserService(UserService userService) { this.userService = userService; } public String execute() { userService.save(); return null; } }
5. 业务逻辑
public class UserService { private UserDao userDao; // = new UserDao(); public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void save() { userDao.save(); } }
6.持久层
public class UserDao { public void save() { System.out.println("DB:保存用户..."); } }
spring自动装配
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。