Spring自动装配注解@Autowired

x33g5p2x  于2021-03-14 发布在 Spring  
字(1.3k)|赞(0)|评价(0)|浏览(358)

自动装配:
@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文件的声明部分有一个约束。这个是全局的约束。是为了避免繁琐性的重复工作而设置的,我想很容易看懂。在此不多说了。

相关文章