Autowired.java
package com.cup.spring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Autowired {
}
BeanDefinition.java
package com.cup.spring;
public class BeanDefinition {
private Class clazz;
private String Scope;
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public String getScope() {
return Scope;
}
public void setScope(String scope) {
Scope = scope;
}
}
BeanNameAware.java
package com.cup.spring;
public interface BeanNameAware {
void setBeanName(String name);
}
BeanPostProcessor.java
package com.cup.spring;
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName);
Object postProcessAfterInitialization(Object bean, String beanName);
}
Component.java
package com.cup.spring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Component {
String value() default "";
}
ComponentScan.java
package com.cup.spring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentScan {
String value();
}
InitializingBean.java
package com.cup.spring;
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
Scope.java
package com.cup.spring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Scope {
String value();
}
SiheyuanApplicationContext.java
package com.cup.spring;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SiheyuanApplicationContext {
private Class configClass;
private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>(); //单例池
private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(); //
private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();
public SiheyuanApplicationContext(Class configClass) {
this.configClass = configClass;
//解析配置类
//ComponentScan注解--->扫描路径--->扫描--->Beandefinition--->BeanDefinitionMap
scan(configClass);
for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
String beanName = entry.getKey();
BeanDefinition beanDefinition = entry.getValue();
if (beanDefinition.getScope().equals("singleton")) {
Object bean = createBean(beanName, beanDefinition); //单例 bean
singletonObjects.put(beanName, bean);
}
}
}
public Object createBean(String beanName, BeanDefinition beanDefinition) {
Class clazz = beanDefinition.getClazz();
try {
Object instance = clazz.getDeclaredConstructor().newInstance();
// 依赖注入
for (Field declaredField : clazz.getDeclaredFields()) {
if (declaredField.isAnnotationPresent(Autowired.class)) {
Object bean = getBean(declaredField.getName());
declaredField.setAccessible(true);
declaredField.set(instance, bean);
}
}
// Aware回调
if (instance instanceof BeanNameAware) {
((BeanNameAware)instance).setBeanName(beanName);
}
for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
}
// 初始化
if (instance instanceof InitializingBean) {
((InitializingBean)instance).afterPropertiesSet();
}
for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
}
// BeanPostProcessor
return instance;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void scan(Class configClass) {
ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
String path = componentScanAnnotation.value(); //扫描路径
path = path.replace(".", "/");
// 扫描
// Bootstarp---> jre/lib
// Ext---------> jre/ext/lib
// App---------> classpath
ClassLoader classLoader = SiheyuanApplicationContext.class.getClassLoader();
URL url = classLoader.getResource(path);
File file = new File(url.getFile());
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File f : listFiles) {
String fileName = f.getAbsolutePath();
if (fileName.endsWith(".class")) {
String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
className = className.replace("\\", ".");
try {
Class<?> aclass = classLoader.loadClass(className);
if (aclass.isAnnotationPresent(Component.class)) {
// 表示当前这个类是一个bean
// 解析类,判断当前的bean是单例bean,还是prototype的bean
// BeanDefinition
if (BeanPostProcessor.class.isAssignableFrom(aclass)) {
BeanPostProcessor instance = (BeanPostProcessor) aclass.getDeclaredConstructor().newInstance();
beanPostProcessorList.add(instance);
}
Component componentAnnotation = aclass.getDeclaredAnnotation(Component.class);
String beanName = componentAnnotation.value();
BeanDefinition beanDefinition = new BeanDefinition();
beanDefinition.setClazz(aclass);
if (aclass.isAnnotationPresent(Scope.class)) {
Scope scopeAnnotation = aclass.getDeclaredAnnotation(Scope.class);
beanDefinition.setScope(scopeAnnotation.value());
} else { //单例
beanDefinition.setScope("singleton");
}
beanDefinitionMap.put(beanName, beanDefinition);
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
public Object getBean(String beanName) {
if (beanDefinitionMap.containsKey(beanName)) {
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition.getScope().equals("singleton")) {
Object o = singletonObjects.get(beanName);
return o;
} else {
// 创建 bean 对象
Object bean = createBean(beanName, beanDefinition);
return bean;
}
} else { // 不存在对应的 bean
throw new NullPointerException();
}
}
}
OrderService.java
package com.cup.siheyuan.service;
import com.cup.spring.Component;
@Component("orderService")
//@Scope("prototype")
public class OrderService {
}
UserService.java
package com.cup.siheyuan.service;
public interface UserService {
void test();
}
UserServiceImpl.java
package com.cup.siheyuan.service;
import com.cup.spring.*;
@Component("userService")
//@Scope("prototype")
public class UserServiceImpl implements UserService {
@Autowired
private OrderService orderService;
private String beanName;
private String name;
public void test() {
System.out.println(orderService);
//System.out.println(beanName);
System.out.println(name);
}
/*@Override implements BeanPostProcessor
public void afterPropertiesSet() throws Exception {
System.out.println("初始化...");
}*/
/*@Override implements BeanNameAware
public void setBeanName(String name) {
beanName = name;
}*/
public void setName(String name) {
this.name = name;
}
}
SiheyuanBeanPostProcessor.java
package com.cup.siheyuan.service;
import com.cup.spring.BeanPostProcessor;
import com.cup.spring.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@Component
public class SiheyuanBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
/*if (beanName.equals("userService")) {
System.out.println("初始化前...");
((UserServiceImpl)bean).setName("四合院好帅!!");
}*/
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println("初始化后...");
if ("userService".equals(beanName)) {
Object proxyInstance = Proxy.newProxyInstance(SiheyuanBeanPostProcessor.class.getClassLoader(),
bean.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理逻辑");
return method.invoke(bean, args);
}
});
return proxyInstance;
}
return bean;
}
}
AppConfig.java
package com.cup.siheyuan;
import com.cup.spring.ComponentScan;
@ComponentScan("com.cup.siheyuan.service")
public class AppConfig {
}
Test.java
package com.cup.siheyuan;
import com.cup.siheyuan.service.UserService;
import com.cup.spring.SiheyuanApplicationContext;
public class Test {
public static void main(String[] args) {
SiheyuanApplicationContext applicationContext = new SiheyuanApplicationContext(AppConfig.class);
UserService userService = (UserService) applicationContext.getBean("userService");
UserService userService1 = (UserService) applicationContext.getBean("userService");
System.out.println(userService);
System.out.println(userService1);
userService.test();
}
}