文章目录
本节的主要是解析Spring注解底层的实现,看看Spring是如何通过注解来进行实例化的。我们通过一个自定义注解ComponentScan来代替component-scan,然后通过一个配置类ZhlSpringConfig来代替applicationContext.xml,ZhlSpringApplicationContext这个类来模拟Spring容器。
1. 思路分析
在代码实现之前,需要说明的是,我们是实例化com.zhl.spring.component包下标有注解的类。这个包下有5个类,如下图,AA类没有注解,那么我们最后应该在容器中看到4个对象。
AA类
/**
* @author zhl
* @version 1.0
*/
public class AA {
}
MyComponent类
package com.zhl.spring.component;
import org.springframework.stereotype.Component;
/**
* @author zhl
* @version 1.0
* @Component 标识该类是一个组件, 是一个通用的注解
*/
@Component
public class MyComponent {
}
UserAction类
package com.zhl.spring.component;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
/**
* @author zhl
* @version 1.0
* @Controller 标识该类是一个控制器Controller, 通常这个类是一个Servlet
*/
@Controller
public class UserAction {
}
UserDao类
package com.zhl.spring.component;
import org.springframework.stereotype.Repository;
/**
* @author zhl
* @version 1.0
* 使用 @Repository 标识该类是一个Repository是一个持久化层的类/对象
*/
@Repository
public class UserDao {
}
UserService类
package com.zhl.spring.component;
import org.springframework.stereotype.Service;
/**
* @author zhl
* @version 1.0
* @Service 标识该类是一个Service类/对象
*/
@Service
public class UserService {
//方法..
public void hi(){
System.out.println("UserService hi()~");
}
}
2. 代码实现
2.1 创建注解ComponentScan
package com.zhl.spring.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO
*
* @Author zhl
* @Date 2023/3/7 11:08
* @Desc: 创建一个注解,这个注解相当于component-scan ,需要传入一个包路径
**/
@Retention(RetentionPolicy.RUNTIME) // 指明注解在运行时起作用
@Target(ElementType.TYPE) // 指明注解的作用范围 类/注解/枚举/接口
public @interface ComponentScan {
String value() default "";
}
2.2 创建配置类ZhlSpringConfig
package com.zhl.spring.annotation;
/**
* TODO
*
* @Author zhl
* @Date 2023/3/7 11:10
* @Desc: 这个类相当于applicationContext.xml
**/
@ComponentScan(value = "com.zhl.spring.component")
public class ZhlSpringConfig {
}
2.3 创建容器类ZhlSpringApplicationContext
package com.zhl.spring.annotation;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.File;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
/**
* TODO
*
* @Author zhl
* @Date 2023/3/7 11:12
* @Desc: 这个类相当于IOC容器,传入配置类的class对象,获取到包路径然后进行容器的初始化
**/
public class ZhlSpringApplicationContext {
private Class configClass;
private final ConcurrentHashMap<String,Object> ioc = new ConcurrentHashMap<>();
public ZhlSpringApplicationContext(Class configClass) {
this.configClass = configClass;
// 1. 获取注解的value值
// 1.1 首先获取到注解对象
ComponentScan declaredAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
// 1.2 然后通过注解对象获取到value值
String path = declaredAnnotation.value(); // path=com.zhl.spring.component
// 2. 通过类加载器获取资源路径
ClassLoader classLoader = ZhlSpringApplicationContext.class.getClassLoader();
URL resource = classLoader.getResource(path.replace(".", "/"));
String resourcePath = resource.getPath(); // /C:/App/develop/spring-learning/spring5/target/classes/com/zhl/spring/component
File file = new File(resourcePath);
if (file.isDirectory()){
File[] files = file.listFiles();
for (File document : files) {
// 3. 通过资源路径获取到绝对路径
String absolutePath = document.getAbsolutePath(); // C:\App\develop\spring-learning\spring5\target\classes\com\zhl\spring\component\UserAction.class
// 4. 然后绝对路径进行截取,获取到类名
String className = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.indexOf(".class"));
// 5. 然后将包路径和类名进行拼接获取到全类名
String fullClassName = path+"."+className; // com.zhl.spring.component.MyComponent
// 6. 通过全类名获取到class对象,判断类上面是否有注解
try {
Class<?> aClass = classLoader.loadClass(fullClassName);
if (aClass.isAnnotationPresent(Controller.class) ||
aClass.isAnnotationPresent(Service.class) ||
aClass.isAnnotationPresent(Repository.class) ||
aClass.isAnnotationPresent(Component.class)
){
// 7. 如果有注解就进行实例化
Class<?> clazz = Class.forName(fullClassName);
Object o = clazz.newInstance();
// 8. 将实例化的对象放入ioc容器中
ioc.put(StringUtils.uncapitalize(className),o);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
/**
* 提供gentBean方法
* @param key key是类名首字母小写
* @return 返回类的实例化对象
*/
public Object getBean(String key){
return ioc.get(key);
}
}
2.4 创建测试类ZhlSpringApplicationContextTest
/**
* TODO
*
* @Author zhl
* @Date 2023/3/7 11:14
* @Desc:
**/
public class ZhlSpringApplicationContextTest {
public static void main(String[] args) {
ZhlSpringApplicationContext ioc = new ZhlSpringApplicationContext(ZhlSpringConfig.class);
Object userAction = ioc.getBean("userAction");
System.out.println(userAction);
}
}
测试结果:
结果如上图,我们成功的通过自定义注解实现了com.zhl.spring.component包下各类的实例化,并把实例化对象放入了容器中。