[ Spring Boot ] Bean 单例注入

Spring Boot 注入Bean 一、@Bean方式
1、在WebMvcConfigurerAdapter的子类中添加@Bean,返回实例对象即可
package cn.com.showclear.plan.impl.plan;

/**
 * 测试
 *
 * @author YF-XIACHAOYANG
 * @date 2017/12/13 18:04
 */
public class TestBean {

    private String name;

    /*可以自定义构造器*/
    public TestBean(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public TestBean setName(String name) {
        this.name = name;
        return this;
    }

    public void hello() {
        System.out.println(this.name);
    }
}

@Bean注入

package cn.com.showclear.config;

@SpringBootApplication
@ComponentScan(basePackages = "cn.com.showclear")
@EnableScheduling
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    ...

    @Bean
    public TestBean getTestBean() {
        return new TestBean("hello bean1!");
    }
}
2、使用@Autowired引用TestBean
@RestController
@RequestMapping("/data/plan/config/")
public class PlanConfigController {

    @Autowired
    private TestBean testBean;
    
     /**
     * 加载预案应急事件标签组[含有组内标签信息]
     *
     * @return
     */
    @RequestMapping(value = "loadTagGroupList", method = RequestMethod.POST)
    public RespMapJson loadTagGroupList(String groupName) {
        testBean.hello();
        return planConfigService.load(planHandleDeliver.getTagConfigHandle().init(this, groupName));
    }
2、@Component方式
1、Bean定义
package cn.com.showclear.plan.impl.plan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 测试
 *
 * @author YF-XIACHAOYANG
 * @date 2017/12/13 18:04
 */
@Component
public class TestBean2 {

    @Autowired
    private TestBean testBean;

    private String name;

    /**
     * 构造器必须是无参构造器
     */
    public TestBean2() {
        this.name ="TestBean2";
    }

    public String getName() {
        return name;
    }

    public TestBean2 setName(String name) {
        this.name = name;
        return this;
    }

    public void hello() {
        System.out.println(name);
    }

    public void hello2() {
        System.out.println(testBean.getName());
    }
}
2、使用方式和方式一相同
...
    @Autowired
    private TestBean2 testBean2;

    /**
     * 加载预案应急事件标签组[含有组内标签信息]
     *
     * @return
     */
    @RequestMapping(value = "loadTagGroupList", method = RequestMethod.POST)
    public RespMapJson loadTagGroupList(String groupName) {
        testBean2.hello();
        testBean2.hello2();
        return planConfigService.load(planHandleDeliver.getTagConfigHandle().init(this, groupName));
    }

console:

[ Spring Boot ] Bean 单例注入

更多

扫码关注“架构探险之道”,获取更多源码和文章资源

[ Spring Boot ] Bean 单例注入

知识星球(扫码加入获取源码和文章资源链接)

[ Spring Boot ] Bean 单例注入

 

上一篇:手写springboot属于自己的starter源码


下一篇:手写web服务器:定义Configuration和Bean注解,实现更灵活的类注入