1. 程式人生 > >[ 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: