1. 程式人生 > >Spring學習系列(二) 自動化裝配Bean

Spring學習系列(二) 自動化裝配Bean

can one bean 工作 顯式 實例 cnblogs con frame

一、Spring裝配-自動化裝配

@[email protected]

通過spring註解(@Component)來表明該類會作為組件類,並告知Spring要為這類創建bean,不過組件掃描默認是不啟動的,需要顯式的配置Spring,從而命令Spring去尋找帶有(@Component)註解的類,並為其創建bean。

1、定義接口

package com.seven.springTest.service;

public interface HelloWorldApi {
    public void sayHello();
}

2、定義接口的實現類

package com.seven.springTest.service.impl;

import org.springframework.stereotype.Component; import com.seven.springTest.service.HelloWorldApi; @Component //通過註解指定該類組件類,告知spring要為它創建Bean public class PersonHelloWorld implements HelloWorldApi { @Override public void sayHello() { System.out.println("Hello World,This Is Person!"); } }

3、前面說過了,spring並不能自動啟用組件掃描,需要進行顯式的配置,這裏通過java類來進行顯式的配置,定義java配置類HelloWorldConfig,在配置類中我們沒有顯式的聲明任何bean,[email protected]

package com.seven.springTest;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan   
// 啟用組件掃描 public class HelloWorldConfig { }

現在所有的工作已經完成,我們來測試下

package com.seven.springTest.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.seven.springTest.HelloWorldConfig;
import com.seven.springTest.service.HelloWorldApi;

public class HelloWorldTest {

    public static void main(String[] args) {
        //1. 聲明Spring上下文,采用java配置類
        ApplicationContext ac = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        //2. 聲明Spring應用上下文,采用xml配置
        //ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        //通過Spring上下文獲取Bean,在這裏Spring通過自動掃描發現了PersonHelloWorld的實現,並自動創建bean。
        HelloWorldApi hwapi = ac.getBean(HelloWorldApi.class);
        //通過sayHello()的輸入內容可以看到,hwapi為PersonHelloWorld的實例
        hwapi.sayHello();
    }
}

Spring學習系列(二) 自動化裝配Bean