美文网首页
springBoot @Bean 注册组件

springBoot @Bean 注册组件

作者: EricDD | 来源:发表于2018-07-16 21:41 被阅读0次

    springBoot 添加组件,不需要再编写spring.xml配置文件。
    @Configuration 指明当前类是一个配置类,替代spring配置文件。
    @Bean 对应xml配置文件中的<bean></bean>标签。将方法的返回值添加到容器中。容器中的这个组件的id就是方法名。

    示例代码:

    @Configuration
    public class MyConfig {
        @Bean
        public HelloService helloService(){
            System.out.println("添加helloService 组件");
            return new HelloService();
        }
    }
    
    @RestController
    @RequestMapping("/home")
    public class HomeController {
        @Autowired
        private HelloService helloService;
        @Autowired
        private ApplicationContext ioc;
        @GetMapping("hello")
        public Map<String,Object> hello(){
           boolean  isHas = ioc.containsBean("helloService");
           String result = helloService.sayHello();
           Map<String,Object> map = new HashMap<>();
           map.put("isHas",isHas);
           map.put("result",result);
           return map;
        }
    }
    
    {
        "result": "hello",
        "isHas": true
    }
    

    相关文章

      网友评论

          本文标题:springBoot @Bean 注册组件

          本文链接:https://www.haomeiwen.com/subject/gjripftx.html