您的位置:首页 > 编程语言 > Java开发

Spring入门Blog[六、Spring自动装配注解@Autowired]

2015-12-23 11:18 741 查看
转自:http://blog.csdn.net/zhang6622056/article/details/7697882

自动装配:
@Autowired使用自动装配的方式。将bean容器里面的值自动注入到bean中。

案例:
1、	Java文件:
public class UserAction {
@Autowired
private UserService userService;
//set方法还是不能缺的,因为autowired也是用setter注入的
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser(){
userService.HelloWorld();
}
}

2、	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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-autowire="byName">

<bean id="userDao" class="com.spring.dao.UserDaoImpl"></bean>

<bean id="userService" class="com.spring.service.UserServiceImpl" scope="prototype">
<property name="userDao" ref="userDao"></property>
</bean>

<!-- 不用再指定property,这里指明autowire就可以了。 -->
<bean id="userAction" class="com.spring.action.UserAction" autowire="byName">
</bean>

</beans>
值得注意的是。上面的这个byName还有一种方式为byType。
还有它标注的范围。不难看到在xml文件的声明部分有一个约束。这个是全局的约束。是为了避免繁琐性的重复工作而设置的,我想很容易看懂。在此不多说了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: