引言
在开发软件的过程中,一些开发者可能会直接将类似数据库的连接参数(如URL、用户名和密码)或者服务器的端口号直接编入源代码中,在SpringBoot中,我们可以把硬编码的配置信息迁移到application.yml中,这样可以使我们的代码更清晰,易于维护和扩展。在不绑定实体类的情况下,可以使用以下两种方法:
方式一:对于非静态的属性直接使用@Value注入
对于非静态的属性:
首先在application.yml配置文件中进行配置:
#ConnectionPool配置
connectionpool:
port: 端口号
incrementalConnections: 你的每次扩容增加的连接数
maxConnections: 最大连接数
然后直接在这个类中直接注入:
/**
* 端口号
*/
@Value("${connectionpool.port}")
private Integer port;
/**
* 每次扩容增加几个连接
*/
@Value("${connectionpool.incrementalConnections}")
private int incrementalConnections;
/**
* 最大连接数
*/
@Value("${connectionpool.maxConnections}")
private int maxConnections;
方式二:对于静态的属性使用@Value注入
对于静态属性不能直接使用@Value注解进行注入,因为@Value注解是在实例化Bean时进行注入的,而静态属性是在类加载时初始化的。所以我们可以使用如下方法进行配置,以减少代码量。
首先依然是先在application.yml配置文件中进行配置:
shellexecutil:
host: 指定应用程序要连接的主机地址
port: 端口号
username: root
password: root
然后在这个类中进行注入:
protected static String host;
protected static int port;
protected static String username;
protected static String password;
@Autowired
public void setProperties(
@Value("${shellexecutil.host}") String host,
@Value("${shellexecutil.port}") int port,
@Value("${shellexecutil.username}") String username,
@Value("${shellexecutil.password}") String password) {
ShellExecUtil.host = host;
ShellExecUtil.port = port;
ShellExecUtil.username = username;
ShellExecUtil.password = password;
}