例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;
}
}
本文详细介绍SpringBoot中@Component、@ConfigurationProperties与@Bean的使用方法,包括如何通过配置文件读取属性值,以及如何在控制器中注入并使用这些组件。
1860

被折叠的 条评论
为什么被折叠?



