当前位置:编程学习 > JAVA >>

spring用annotation-autowire配置

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
xmlns:context="http://www.springframework.org/schema/context" ><!-- 使用annotation需加上面三行的该内容和下面的一行 -->
 
<context:annotation-config/>
 
<bean id="u" class="annotation.autoWire.UserDAOImpl">
</bean>
<bean id="u2" class="annotation.autoWire.UserDAOImpl">
</bean>
<bean id="userService" class="annotation.autoWire.UserService">
</bean>
 
</beans>
 
 
User,java
 
package annotation.autoWire;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
 
 
 
 
 
 
 
UserDAO.java
 
package annotation.autoWire;
public inte易做图ce UserDAO {
public void save(User user);
}
 
 
 
 
 
UserDAOImpl.java
 
package annotation.autoWire;
public class UserDAOImpl implements UserDAO {
public void save(User user) {
System.out.println("user saved!");
}
}
 
 
 
 
 
UserService.java
 
package annotation.autoWire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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//需配置在setter方法上
public void setUserDAO(@Qualifier("u2") UserDAO userDAO) {
this.userDAO = userDAO;
}
 
public void destroy() {
System.out.println("destroy");
}
}
 
 
 
 
 
UserServiceTest.java
 
package annotation.autoWire;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserServiceTest {
@Test
public void testAnnotationAutoWire() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("annotation/autoWire/annotationAutoWire.xml");
UserService service = (UserService)ctx.getBean("userService");
service.add(new User());
System.out.println(service.getUserDAO());
}
}
补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,