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

来源:互联网 发布:word2010 mac 破解版 编辑:程序博客网 时间:2024/06/11 13:29

转自:http://blog.csdn.net/zhang6622056/article/details/7697882

自动装配:@Autowired使用自动装配的方式。将bean容器里面的值自动注入到bean中。案例:1、Java文件:public class UserAction {@Autowiredprivate 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文件的声明部分有一个约束。这个是全局的约束。是为了避免繁琐性的重复工作而设置的,我想很容易看懂。在此不多说了。


2 0
原创粉丝点击