@Configuration & @Bean

使用@Configuration使这个类作为配置类

使用@Bean将对象加入容器中

 

代码部分:

package com.shishi.firstservice.service;

// 这里并没有将HelloService加入容器
public class HelloService {

}

 

// 配置类,将HelloService加入容器
@Configuration
public class MyAppConfig {
    @Bean
    public HelloService helloService() {
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}

启动项目:

 

 测试这个有没有加入容器:

@RestController
public class FirstController {
    @Autowired
    ApplicationContext ioc;


    @RequestMapping("/hello")
    public String helloWorld() {
        return ioc.containsBean("helloService") ? "contains" : "not contains";
    }
}

 

posted @ 2020-10-08 21:52  圣金巫灵  阅读(116)  评论(0编辑  收藏  举报