其他分享
首页 > 其他分享> > [ Spring Boot ] Bean 单例注入

[ 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:

更多

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

在这里插入图片描述

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

在这里插入图片描述

 

标签:return,name,Spring,Boot,Bean,TestBean,public,String
来源: https://blog.51cto.com/u_15263565/2884871