什么是spring?
Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。
Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
- 目的:解决企业应用开发的复杂性
- 功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
- 范围:任何Java应用
- 它是一个容器框架,用来装javabean(java对象),中间层框架(万能胶)可以起一个连接作用,比如说把Struts和hibernate粘合在一起运用。简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
spring生命周期图
深入理解spring(手写ComponentScan、Component、AutoWried、Scope )注解
工程结构
App类为测试类:代码如下
public class App
{
public static void main( String[] args )
{
TestApplicationContext testApplicationContext = new TestApplicationContext(AppConfig.class);
UserService user1 = (UserService)testApplicationContext.getBean("userService");
UserService user2 = (UserService)testApplicationContext.getBean("userService");
OrderService orderService1 = (OrderService)user1.getOrderService();
OrderService orderService2 = (OrderService)user2.getOrderService();
System.out.println(orderService1);
System.out.println(orderService2);
}
}
TestApplicationContext类如下
public class TestApplicationContext {
private Class clazz;
//TODO单列池
private ConcurrentHashMap<String, Object> singletonObject = new ConcurrentHashMap<>();
//TODO Bean的定义信息
private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
public TestApplicationContext(Class clazz) {
this.clazz = clazz;
//扫描ComponentScan注解信息,添加到BeanDefinition
scan(clazz);
for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
String beanName = entry.getKey();
BeanDefinition beanDefinition = entry.getValue();
if (beanDefinition.getScope().equals("singleton")) {
Object bean = this.createBean(beanDefinition);
singletonObject.put(beanName, bean);
}
}
}
public Object createBean(BeanDefinition beanDefinition) {
Class clazz = beanDefinition.getClazz();
Object instance = null;
try {
instance = clazz.getDeclaredConstructor().newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
if (field.isAnnotationPresent(AutoWried.class)) {
Object bean = this.getBean(field.getName());
field.set(instance, bean);
}
}
return instance;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return instance;
}
private void scan(Class clazz) {
ComponentScan annotation = (ComponentScan) clazz.getDeclaredAnnotation(ComponentScan.class);
//获取到ComponentScan中的路径 并且将.转为/
String path = annotation.value().replace(".", "/");
//获取TestApplicationContext的加载路径
ClassLoader classLoader = TestApplicationContext.class.getClassLoader();
URL resource = classLoader.getResource(path);
File file = new File(resource.getFile());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
String fileName = f.getAbsolutePath();
if (fileName.endsWith(".class")) {
String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
String pathName = className.replace("\\", ".");
try {
Class<?> aClass = classLoader.loadClass(pathName);
if (aClass.isAnnotationPresent(Component.class)) {
//表示当前类是一个bean
//判断当前bean是单列bean还是多列
Component componentAnno = aClass.getDeclaredAnnotation(Component.class);
String beanName = componentAnno.value();
BeanDefinition beanDefin = new BeanDefinition();
beanDefin.setClazz(aClass);
if (aClass.isAnnotationPresent(Scope.class)) {
Scope scopeAnno = aClass.getDeclaredAnnotation(Scope.class);
beanDefin.setScope(scopeAnno.value());
} else {
beanDefin.setScope("singleton");
}
beanDefinitionMap.put(beanName, beanDefin);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
public Object getBean(String beanName) {
if (beanDefinitionMap.containsKey(beanName)) {
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition.getScope().equals("singleton")) {
Object o = singletonObject.get(beanName);
return o;
} else {
//创建Bean
Object bean = this.createBean(beanDefinition);
return bean;
}
} else {
throw new NullPointerException();
}
}
}
AppConfig类如下
@ComponentScan("com.sumeng.service")
public class AppConfig {
}
BeanDefinition类如下
public class BeanDefinition {
private Class clazz;
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
private String scope;
}
注解类:AutoWried,ComponentScan,Component,Scope 如下
/** AutoWried */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoWried {
}
/** Component */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
String value() default "";
}
/** ComponentScan */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentScan {
String value ();
}
/** Scope */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Scope {
String value() ;
}