4.0.0
com.weichai
SpringIocByAnnotation
0.0.1-SNAPSHOT
jar
SpringIocByAnnotation
http://maven.apache.org
UTF-8
org.springframework
spring-core
4.2.0.RELEASE
org.springframework
spring-context
4.2.0.RELEASE
org.springframework
spring-aop
4.2.0.RELEASE
org.springframework
spring-orm
4.2.0.RELEASE
org.springframework
spring-jdbc
4.2.0.RELEASE
org.aspectj
aspectjrt
1.8.0
org.aspectj
aspectjweaver
1.8.0
cglib
cglib
3.2.0
com.mchange
c3p0
0.9.5.2
mysql
mysql-connector-java
5.1.45
org.apache.commons
commons-dbcp2
2.5.0
dom4j
dom4j
1.6.1
commons-lang
commons-lang
2.6
junit
junit
3.8.1
test
3.1 注解
package com.weichai.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解 注入到Spring容器
* @author linhaiy
* @date 2019.01.25
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtService {
}
package com.weichai.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解 从Spring容器获取bean
* @author linhaiy
* @date 2019.01.25
*/
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtResource {
}
3.2 常用反射工具类
package com.weichai.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 常用反射工具类
* @author linhaiy
* @date 2019.01.25
*/
public class ClassUtil {
/**
* 从包package中获取所有的Class
*
* @param packageName
* @return
*/
public static List> getClasses(String packageName) {
List> classes = new ArrayList>(); // 第一个class类的集合
boolean recursive = true; // 是否循环迭代
String packageDirName = packageName.replace('.', '/'); // 获取包的名字 并进行替换
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
* @param packageName
* @param filePath
* @param recursive
* @param classes
*/
private static void findAndAddClassesInPackageByFile(String packageName, String packagePath,
final boolean recursive, List> classes) {
// TODO Auto-generated method stub
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
/**
* 取得某一类所在包的所有类名 不含迭代
* @param classLocation
* @param packageName
* @return
*/
public static String[] getPackageAllClassName(String classLocation, String packageName) {
// 将packageName分解
String[] packagePathSplit = packageName.split("[.]");
String realClassLocation = classLocation;
int packageLength = packagePathSplit.length;
for (int i = 0; i < packageLength; i++) {
realClassLocation = realClassLocation + File.separator + packagePathSplit[i];
}
File packeageDir = new File(realClassLocation);
if (packeageDir.isDirectory()) {
String[] allClassName = packeageDir.list();
return allClassName;
}
return null;
}
/**
* 取得某个接口下所有实现这个接口的类
* @param c
* @return
*/
public static List getAllClassByInterface(Class c) {
List returnClassList = null;
if (c.isInterface()) {
// 获取当前的包名
String packageName = c.getPackage().getName();
// 获取当前包下以及子包下所以的类
List> allClass = getClasses(packageName);
if (allClass != null) {
returnClassList = new ArrayList();
for (Class classes : allClass) {
// 判断是否是同一个接口
if (c.isAssignableFrom(classes)) {
// 本身不加入进去
if (!c.equals(classes)) {
returnClassList.add(classes);
}
}
}
}
}
return returnClassList;
}
}
3.3 手写Spring专题 注解版本注入bean核心类
package com.weichai.springimpl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
import com.weichai.annotation.ExtService;
import com.weichai.util.ClassUtil;
/**
* 手写Spring专题 注解版本注入bean
* @author linhaiy
* @date 2019.01.25
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ClassPathXmlApplicationContext {
private String packageName; //扫包范围
ConcurrentHashMap initBean = null;
public ClassPathXmlApplicationContext(String packageName) {
super();
this.packageName = packageName;
}
/**
* 使用beanID查找对象(SringIOC注解实现主类 )
* @param beanId
* @return
* @throws Exception
*/
public Object getBean(String beanId) throws Exception {
List listClassAnnotation = findClassByExisService(); // 1.使用反射机制获取该包下所有的类已经存在bean的注解类
if(listClassAnnotation == null || listClassAnnotation.isEmpty()) {
throw new Exception("没有需要初始化的bean");
}
initBean = initBean(listClassAnnotation); // 2.使用Java反射机制初始化对象
if (initBean == null || initBean.isEmpty()) {
throw new Exception("初始化bean为空!");
}
Object object = initBean.get(beanId); // 3.使用beanID查找查找对应bean对象
attriAssign(object); // 4.使用反射读取类的属性,赋值信息
return object;
}
/**
* 使用反射读取类的属性,赋值信息
* @param object
*/
private void attriAssign(Object object) throws IllegalArgumentException, IllegalAccessException {
// TODO Auto-generated method stub
Class extends Object> classInfo = object.getClass(); // 1.获取类的属性是否存在 获取bean注解
Field[] declaredFields = classInfo.getDeclaredFields();
for(Field field : declaredFields) {
String name = field.getName(); // 属性名称
Object bean = initBean.get(name); // 2.使用属性名称查找bean容器赋值
if(bean !=null) {
field.setAccessible(true); // 私有访问允许访问
field.set(object, bean); // 给属性赋值
continue;
}
}
}
/**
* 初始化bean对象,ConcurrentHashMap保存
* @param listClassAnnotation
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
private ConcurrentHashMap initBean(List listClassAnnotation) throws InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();
for(Class classInfo : listClassAnnotation) {
Object newInstance = classInfo.newInstance(); // 初始化对象
String beanId = toLowerCaseFirstOne(classInfo.getSimpleName()); // 获取父类名称
concurrentHashMap.put(beanId, newInstance);
}
return concurrentHashMap;
}
/**
* 首字母转小写
* @param simpleName
* @return
*/
private String toLowerCaseFirstOne(String s) {
// TODO Auto-generated method stub
if (Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
/**
* 使用反射机制获取该包下所有的类已经存在bean的注解类
* @return
* @throws Exception
*/
private List findClassByExisService() throws Exception {
// TODO Auto-generated method stub
if(StringUtils.isEmpty(packageName)) { // 1.使用反射机制获取该包下所有的类
throw new Exception("扫包地址不能为空!");
}
List> classByPackageName = ClassUtil.getClasses(packageName); // 2.使用反射技术获取当前包下所有的类
List exisClassesAnnotation = new ArrayList(); // 3.存放类上有bean注入注解
// 4.判断该类上属否存在注解
for(Class classInfo : classByPackageName) {
ExtService extService = (ExtService) classInfo.getDeclaredAnnotation(ExtService.class);
if(extService !=null) {
exisClassesAnnotation.add(classInfo);
continue;
}
}
return exisClassesAnnotation;
}
}
4.1 一般测试方式相关代码
package com.weichai.service;
public interface OrderService {
public void addOrder();
}
package com.weichai.service;
import com.weichai.annotation.ExtService;
@ExtService
public class OrderServiceImpl implements OrderService {
public void addOrder() {
// TODO Auto-generated method stub
System.out.println("欢迎进入addOrder方法!");
}
}
package com.weichai.service;
public interface UserService {
public void add();
}
package com.weichai.service;
import com.weichai.annotation.ExtResource;
import com.weichai.annotation.ExtService;
@ExtService
public class UserServiceImpl implements UserService {
@ExtResource
private OrderService orderServiceImpl;
public void add() {
// TODO Auto-generated method stub
orderServiceImpl.addOrder();
System.out.println("我是使用反射机制调用order的执行方法!");
}
}
package com.weichai.SpringIocByAnnotation;
import com.weichai.service.UserService;
import com.weichai.springimpl.ClassPathXmlApplicationContext;
/**
* SpringIOC注解实现测试
* @author linhaiy
* @date 2019.01.25
*/
public class SpringIocTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("com.weichai.service");
UserService userService = (UserService) app.getBean("userServiceImpl");
userService.add();
}
}
4.2 数据库操作依赖注入测试
package com.weichai.entity;
import java.io.Serializable;
/**
* 用户实体类
* @author linhaiy
* @date 2019.01.25
*/
public class User implements Serializable {
private Integer id;
private String userName;
private String userPwd;
private Integer age;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", age=" + age + ", address="
+ address + "]";
}
}
package com.weichai.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.weichai.annotation.ExtService;
import com.weichai.entity.User;
/**
* 数据持久层接口接入
* @author linhaiy
* @date 2019.01.25
*/
@ExtService
public class UserDao {
public String SQL = "SELECT * FROM USER";
public List findAll(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
System.out.println("底层查询。。。。。。");
List list = jdbcTemplate.query(SQL, new RowMapper() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUserName(rs.getString("userName"));
user.setUserPwd(rs.getString("userPwd"));
user.setAge(rs.getInt("age"));
user.setAddress(rs.getString("address"));
return user;
}
});
return list;
}
}
package com.weichai.dao;
import java.util.List;
import com.weichai.annotation.ExtResource;
import com.weichai.annotation.ExtService;
import com.weichai.entity.User;
@ExtService
public class UserService {
@ExtResource
private UserDao userDao;
public List findAll(){
System.out.println("进入查询。。。。。。");
return userDao.findAll();
}
}
package com.weichai.SpringIocByAnnotation;
import java.util.List;
import com.weichai.dao.UserService;
import com.weichai.entity.User;
import com.weichai.springimpl.ClassPathXmlApplicationContext;
public class UserTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("com.weichai.dao"); //输入要扫描的包
UserService userService = (UserService) app.getBean("userService");
List list = userService.findAll();
System.out.println(list);
}
}