@Bean @Component 代码样例

例1:使用@Component

在一个spring boot项目中定义了一个@Compoent类 TestComponent

@Component
public class TestComponent {
    public String name="123";
}

使用也很简单,但是一定要添加@Autowired,@Autowired告诉spring容器去装配生成TestComponent对象,也就是testComponent

@RestController
public class HelloController {
    @Autowired
    private TestComponent testComponent;

    @RequestMapping("/hello2")
    public String hello2(String name) {
        return "test component "+testComponent.name;
    }
}

例2:Compoent从配置文件读取属性数值

这个例子更实用,可以通过配置文件装配对象

@Component
@ConfigurationProperties(prefix = "helloworld.common")
public class HelloworldCfg {
    private int commonSize;

    public int getCommonSize(){return this.commonSize;}

    public void setCommonSize(int _size){
        this.commonSize=_size;
    }
}

配置文件:application.properties 的内容

helloworld.common.commonSize=29

调用方法

@RestController
public class CircusController {
    @Autowired
    private HelloworldCfg helloworldCfg;
    @RequestMapping("/TestCfg")
    public String TestCfg(){
        return "test config : "+helloworldCfg.getCommonSize();
    }
}

 

例3:使用@Bean

public class TestBean {
    public String name="test bean";
}

@Bean必须放到方法上,不能用来修饰class,而且所在的class必须用@Configuration来修饰 

@Configuration
public class TestBeanCfg {
    @Bean
    public TestBean getTestBean(){
        TestBean testBean=new TestBean();
        testBean.name="changed";
        return testBean;
    }
}

下面的代码是如何使用@Bean

@RestController
public class CircusController {

    @Autowired
    TestBean testBean;

    @RequestMapping("/TestBean")
    public String TestBean(){
        return "test bean : "+testBean.name;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值