Spring再接触 Annotation part1
使用annotation首先得加这两条代码
beans.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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config /> //相当于初始化了四个bean 确保能够识别出annotation <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="u2" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="userService" class="com.bjsxt.service.UserService" > </bean> </beans>
Userservice
package com.bjsxt.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.bjsxt.dao.UserDAO; import com.bjsxt.model.User; public class UserService { private UserDAO userDAO; public void init() { System.out.println("init"); } public void add(User user) { userDAO.save(user); } public UserDAO getUserDAO() { return userDAO; } @Autowired //使用anotation public void setUserDAO(@Qualifier("u") UserDAO userDAO) { //制定具体注入哪一个 this.userDAO = userDAO; } public void destroy() { System.out.println("destroy"); } }