关闭

spring用annotation-autowire配置

标签: springSpring
2802人阅读 评论(0) 收藏 举报
分类:
<?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 interface 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());
}
}

3
0

猜你在找
【直播】机器学习&深度学习系统实战(唐宇迪)
【直播】Kaggle 神器:XGBoost 从基础到实战(冒教授)
【直播回放】深度学习基础与TensorFlow实践(王琛)
【直播】计算机视觉原理及实战(屈教授)
【直播】机器学习之凸优化(马博士)
【直播】机器学习之矩阵(黄博士)
【直播】机器学习之概率与统计推断(冒教授)
【直播】机器学习之数学基础
【直播】TensorFlow实战进阶(智亮)
【直播】深度学习30天系统实训(唐宇迪)
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:267406次
    • 积分:3773
    • 等级:
    • 排名:第8223名
    • 原创:141篇
    • 转载:7篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论