这个小程序主要是为了学习一下Spring annotation注入的写代码方式,另一个目的就是看一下spring是什么时候初始化Bean,实例化Bean,注入Bean的
1:导入Spring的jar包
2:添加ApplicationContext.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 打开Spring的Annotation的支持 -->
<context:annotation-config />
<!-- 设定Spring去哪些包中找Annotation -->
<context:component-scan base-package="com.iocProject" />
</beans>
3:编写User业务处理代码userBLL
package com.iocProject.userBLL;
import com.iocProject.dao.UserDao;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
@Component("userBLL")
public class UserBLL {
private UserDao userDao;
public UserBLL()
{
System.out.println("start construction UserBll");
}
public UserDao getUserDao() {
return userDao;
}
@Resource
public void setUserDao(UserDao userDao) {
System.out.println("start injection userDao");
this.userDao = userDao;
}
public void addUser()
{
System.out.println("start to add user");
this.userDao.AddUser();
}
}
4:编写UserDao处理代码Dao
package com.iocProject.dao;
public interface UserDao {
void AddUser();
}
package com.iocProject.dao;
import org.springframework.stereotype.Component;
@Component
public class UserDaoImpl implements UserDao{
public UserDaoImpl()
{
System.out.println("start construction UserDao");
}
@Override
public void AddUser() {
// TODO Auto-generated method stub
System.out.print("add user dao");
}
}
5:写测试用例(只初始化ApplicationContex配置文件)观察结果
6:写测试用例获取Bean,调用Bean方法观察结果
7:可以发现Spirng在初始化ApplicationContex配置文件就已经实例化了Bean对象而且完成了注入
8:给出测试程序的实例,小弟初学,希望各位大神给出指正