最簡單的手寫spring--簡書

總共大概分為這幾步:有空再補上實現(xiàn)過程的描述

直接上代碼:整體工程就是這樣簡單过椎,項目不引用spring

1婆排、首先是程序入口AppConfig(主要設(shè)置掃描路徑)

@ComponentScan("cn.service")

public class AppConfig {

}

2腋颠、自定義四個注解:@Autowired伊磺,@ComponentScan肆捕,@Scope和@Service

3掌实、定義bean類OrderService和UserService分別在類上加上注解@Service

@Service("orderService")

public class OrderService {

@Autowired

? ? private UserServiceuserService;

? ? public void getUserService(){

System.out.println(userService);

? ? }

}

@Service("userService")

@Scope("prototype")

public class UserService {

}

4、定義AnnotationConfigApplication實例化听想、初始化bean腥刹,填充屬性并將bean寫入單例池

public class AnnotationConfigApplication {

private ConcurrentHashMapbeanDefinitionMap =new ConcurrentHashMap();

? ? private ConcurrentHashMapsingletonObjects =new ConcurrentHashMap();

? ? /**

? ? ? * @Description 根據(jù)啟動配置類加載初始化

? ? ? *

? ? ? * @Param classConfig

? ? ? * @Return

? ? ? * @Author 胡攀

? ? ? */

? ? public AnnotationConfigApplication(Class classConfig) {

//掃描類

? ? ? ? List classes = scan(classConfig);

? ? ? ? //掃描到類之后,解析這個類汉买,Service,BeanDefinition

? ? ? ? for (Class clazz : classes) {

Service service = (Service) clazz.getAnnotation(Service.class);

? ? ? ? ? ? String name = service.value();

? ? ? ? ? ? //獲取Scope注解

? ? ? ? ? ? BeanDefinition beanDefinition =new BeanDefinition();

? ? ? ? ? ? beanDefinition.setClassBean(clazz);

? ? ? ? ? ? if(clazz.isAnnotationPresent(Scope.class)) {

Scope scope = (Scope) clazz.getAnnotation(Scope.class);

? ? ? ? ? ? ? ? beanDefinition.setScope(scope.value());

? ? ? ? ? ? }else{

beanDefinition.setScope("singleton");

? ? ? ? ? ? }

beanDefinitionMap.put(name, beanDefinition);

? ? ? ? }

//遍歷beanDefinitionMap生成bean

? ? ? ? //單例bean直接存到單例池

? ? ? ? for (String beanName :beanDefinitionMap.keySet()) {

BeanDefinition beanDefinition =beanDefinitionMap.get(beanName);

? ? ? ? ? ? if (beanDefinition.getScope().equals("singleton")) {

//生成這個bean

? ? ? ? ? ? ? ? Object bean = createBean(beanDefinition);

? ? ? ? ? ? ? ? singletonObjects.put(beanName,bean);

? ? ? ? ? ? }

}

}

/**

? ? * @Description 創(chuàng)建一個bean

*

? ? * @Param beanDefinition

? ? * @Return Object

? ? * @Author 胡攀

? ? */

? ? private ObjectcreateBean(BeanDefinition beanDefinition){

//生成這個bean

? ? ? ? Class beanClass = beanDefinition.getClassBean();

? ? ? ? //實例化

? ? ? ? try {

Object bean = beanClass.getDeclaredConstructor().newInstance();

? ? ? ? ? ? //填充屬性

? ? ? ? ? ? Field[] fields = beanClass.getDeclaredFields();

? ? ? ? ? ? for (Field field : fields) {

if (field.isAnnotationPresent(Autowired.class)) {

Object attr = getBean(field.getName());

? ? ? ? ? ? ? ? ? ? field.setAccessible(true);

? ? ? ? ? ? ? ? ? ? field.set(bean, attr);

? ? ? ? ? ? ? ? }

}

return bean;

? ? ? ? }catch (InstantiationException e) {

e.printStackTrace();

? ? ? ? }catch (IllegalAccessException e) {

e.printStackTrace();

? ? ? ? }catch (InvocationTargetException e) {

e.printStackTrace();

? ? ? ? }catch (NoSuchMethodException e) {

e.printStackTrace();

? ? ? ? }

return null;

? ? }

/**

? ? * @Description 通過beanName 獲取單例池中的bean

*

? ? * @Param beanName

? ? * @Return

? ? * @Author 胡攀

? ? */

? ? public ObjectgetBean(String beanName) {

BeanDefinition beanDefinition =beanDefinitionMap.get(beanName);

? ? ? ? if("prototype".equals(beanDefinition.getScope())){

return createBean(beanDefinition);

? ? ? ? }else{

Object bean =singletonObjects.get(beanName);

? ? ? ? ? ? if(bean ==null){

Object o = createBean(beanDefinition);

? ? ? ? ? ? ? ? singletonObjects.put(beanName,o);

? ? ? ? ? ? ? ? return o;

? ? ? ? ? ? }else{

return bean;

? ? ? ? ? ? }

}

}

/**

? ? * @Description 根據(jù)啟動類掃描類

? ? *

? ? * @Param classConfig

? ? * @Return

? ? * @Author 胡攀

? ? */

? ? private Listscan(Class classConfig) {

List classList =new ArrayList();

? ? ? ? //掃描類

? ? ? ? ComponentScan componentScan = (ComponentScan) classConfig.getAnnotation(ComponentScan.class);

? ? ? ? String scanPath = componentScan.value();

? ? ? ? scanPath = scanPath.replace(".", "/");

? ? ? ? System.out.println("scanPath:" + scanPath);

? ? ? ? //如何掃描類

? ? ? ? ClassLoader classLoader = AnnotationConfigApplication.class.getClassLoader();

? ? ? ? URL resource = classLoader.getResource(scanPath);

? ? ? ? System.out.println("resource:" + scanPath);

? ? ? ? //獲取文件路徑下的所有文件路徑

? ? ? ? File file =new File(resource.getFile());

? ? ? ? File[] files = file.listFiles();

? ? ? ? for (File f : files) {

//替換為classLoader能識別的包路徑

? ? ? ? ? ? String absolutePath = f.getAbsolutePath();

? ? ? ? ? ? absolutePath = absolutePath.substring(absolutePath.indexOf("cn"), absolutePath.indexOf(".class")).replace("\\", ".");

? ? ? ? ? ? try {

Class clazz = classLoader.loadClass(absolutePath);

? ? ? ? ? ? ? ? System.out.println(clazz);

? ? ? ? ? ? ? ? if (clazz.isAnnotationPresent(Service.class)) {

classList.add(clazz);

? ? ? ? ? ? ? ? }

}catch (ClassNotFoundException e) {

e.printStackTrace();

? ? ? ? ? ? }

}

return classList;

? ? }

}

5衔峰、最后調(diào)用的結(jié)果就是這樣:注意scope注解單例和原型的判斷方式


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蛙粘,隨后出現(xiàn)的幾起案子垫卤,更是在濱河造成了極大的恐慌,老刑警劉巖出牧,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件穴肘,死亡現(xiàn)場離奇詭異,居然都是意外死亡舔痕,警方通過查閱死者的電腦和手機评抚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來伯复,“玉大人慨代,你說我怎么就攤上這事⌒ト纾” “怎么了侍匙?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長叮雳。 經(jīng)常有香客問我想暗,道長妇汗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任说莫,我火速辦了婚禮铛纬,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘唬滑。我一直安慰自己告唆,他們只是感情好,可當我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布晶密。 她就那樣靜靜地躺著擒悬,像睡著了一般。 火紅的嫁衣襯著肌膚如雪稻艰。 梳的紋絲不亂的頭發(fā)上懂牧,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天,我揣著相機與錄音尊勿,去河邊找鬼僧凤。 笑死,一個胖子當著我的面吹牛元扔,可吹牛的內(nèi)容都是我干的躯保。 我是一名探鬼主播,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼澎语,長吁一口氣:“原來是場噩夢啊……” “哼途事!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起擅羞,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤尸变,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后减俏,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體召烂,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年娃承,在試婚紗的時候發(fā)現(xiàn)自己被綠了奏夫。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡草慧,死狀恐怖桶蛔,靈堂內(nèi)的尸體忽然破棺而出匙头,到底是詐尸還是另有隱情漫谷,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布蹂析,位于F島的核電站舔示,受9級特大地震影響碟婆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜惕稻,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一竖共、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧俺祠,春花似錦公给、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蔫缸,卻和暖如春腿准,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拾碌。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工吐葱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人校翔。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓弟跑,卻偏偏與公主長得像,于是被迫代替她去往敵國和親防症。 傳聞我的和親對象是個殘疾皇子窖认,可洞房花燭夜當晚...
    茶點故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容