**配置類 MyAppConfig **
import com.test.springboot.service.HelloService;
import org.springframework.context.annotation.*;
/**
* @Configuration:注解告訴springboot當前類是一個配置類,是來替代之前的spring配置文件。
* 在配置文件中用<bean></bean>標簽添加組件
*/
@Configuration
@ComponentScan(basePackages = {"com.test.springboot"})
public class MyAppConfig {
//將方法的返回值添加到容器中,容器中這個組件默認的ID是方法名
@Bean("helloService")
public HelloService helloService() {
System.out.println("配置類@bean給容器中添加組件了");
return new HelloService();
}
}
**HelloService **類
public class HelloService {
public void say(String name) {
System.out.println("****helloservice***" + name);
}
}
測試類
import com.test.springboot.bean.Person;
import com.test.springboot.service.HelloService;
import config.MyAppConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
/**
* springboot單元測試
* 可以在測試期間很方便的類似編碼一樣進行自動注入等容器的功能
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService() {
System.out.println("****************************************");
ApplicationContext context = new AnnotationConfigApplicationContext(MyAppConfig.class);
HelloService helloService = (HelloService) context.getBean("helloService");
System.out.println(helloService);
boolean flag = context.containsBean("helloService");
System.out.println("bean是否存在:" + flag);
helloService.say("小明");
}
}
執行結果
2019-05-08 17:27:32.553 INFO 2588 --- [ main] c.t.s.SpringBoot02ConfigApplicationTests : No active profile set, falling back to default profiles: default
2019-05-08 17:27:34.786 INFO 2588 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-08 17:27:35.123 INFO 2588 --- [ main] c.t.s.SpringBoot02ConfigApplicationTests : Started SpringBoot02ConfigApplicationTests in 3.134 seconds (JVM running for 4.183)
****************************************
配置類@bean給容器中添加組件了
com.test.springboot.service.HelloService@6eaa21d8
bean是否存在:true
****helloservice***小明
2019-05-08 17:27:35.741 INFO 2588 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Process finished with exit code 0
注解描述:
-
@Configuration: 指明當前類是一個配置類來替代之前的Spring配置文件,Spring boot的配置類,相當於Spring的配置文件。- Spring,通過配置文件添加組件
- Spring boot,通過配置類的方式添加組件
-
@ComponentScan:作用就是根據定義的掃描路徑,把符合掃描規則的類裝配到spring容器中 -
@Bean:將方法的返回值添加到容器中
