SpringBoot配置Bean的两种方式--注解以及配置文件
2023-09-27 14:24:54 时间
一、注解方式
编写实体类:
package com.example.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Created by Loser100 on 2017/10/9.
*/
@Component
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private static final String MSG = "hello";
private String msg = MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
其中Component注解为自动装载,注解ConfigurationProperties的prefix = “hello”可以在application.yml或application.properties中进行赋值,如:hello.msg = Loser100。若不赋值则默认为”hello”!
二、配置文件方式
编写实体:
package com.example.services;
/**
* Created by Loser100 on 2017/10/9.
*/
public class HelloService {
private String msg;
public String sayHello(){
return "HELLO" + msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
rce.META-INF下新建spring.factories文件,内容为:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=main.java.com.example.services.HelloService
三、使用
使用时直接使用@Autowired标签即可,如:
@Autowired
private HelloService helloServiceProperties;
String sayHello(){
return helloServiceProperties.sayHello();
}
附上学习工程截图:
相关文章
- springboot工程的结构
- Idea springboot 配置热部署
- SpringBoot 2.4与tomcat版本、图片上传访问不了
- springboot 整合logback实现日志出入到不同文件当中(含sql输出到制定文件中)
- springboot 打包一定要配置打包插件
- 监控SpringBoot应用的两种方式
- 第二十四章 springboot注入servlet
- SpringBoot学习笔记-16:第十六章-SpringBoot 与监控管理
- SpringBoot自动配置的实现原理
- SpringBoot 多数据库支持:
- springboot中关闭eureka server中已注册服务列表自我保护配置
- SpringBoot参数校验
- SpringBoot 配置 @PropertySource、@ImportResource、@Bean
- Springboot+shiro配置笔记+错误小结
- springboot整合freemarker(转)
- SpringBoot整合MongoDB有无密码连接的yml配置
- SpringBoot配置postgre多数据源(亲测有效!!!)
- [SpringBoot]配置文件①(配置文件格式、yaml配置及读取)
- SpringBoot基础之MockMvc单元测试
- 《Drools7.0.0.Final规则引擎教程》Springboot+规则重新加载
- 在SpringBoot中配置定时任务