<?xml version= encoding=UTF?>
<beans xmlns=
xmlns:xsi=instance
xmlns:p=
xsi:schemaLocation=
beansxsd
contextxsd
xmlns:context= ><! 使用annotation需加上面三行的该内容和下面的一行 >
<context:annotationconfig/>
<bean id=u class=annotationautoWireUserDAOImpl>
</bean>
<bean id=u class=annotationautoWireUserDAOImpl>
</bean>
<bean id=userService class=annotationautoWireUserService>
</bean>
</beans>
Userjava
package annotationautoWire;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
thisusername = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
thispassword = password;
}
}
UserDAOjava
package annotationautoWire;
public interface UserDAO {
public void save(User user)
}
UserDAOImpljava
package annotationautoWire;
public class UserDAOImpl implements UserDAO {
public void save(User user) {
Systemoutprintln(user saved!)
}
}
UserServicejava
package annotationautoWire;
import orgspringframeworkbeansfactoryannotationAutowired;
import orgspringframeworkbeansfactoryannotationQualifier;
public class UserService {
private UserDAO userDAO;
public void init() {
Systemoutprintln(init)
}
public void add(User user) {
userDAOsave(user)
}
public UserDAO getUserDAO() {
return userDAO;
}
@Autowired//需配置在setter方法上
public void setUserDAO(@Qualifier(u) UserDAO userDAO) {
thisuserDAO = userDAO;
}
public void destroy() {
Systemoutprintln(destroy)
}
}
UserServiceTestjava
package annotationautoWire;
import orgjunitTest;
import orgntextApplicationContext;
import orgntextsupportClassPathXmlApplicationContext;
public class UserServiceTest {
@Test
public void testAnnotationAutoWire() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(annotation/autoWire/annotationAutoWirexml)
UserService service = (UserService)ctxgetBean(userService)
serviceadd(new User())
Systemoutprintln(servicegetUserDAO())
}
}