两种springboot配置文件中使用${} 注入值的方法

2022-06-16 10:39:49

1.在springboot中使用System.setProperty设置参数

user:
  user-name: ${username}
  age: ${age}

配置文件是这种写法,我们可以用System.setProperty来设置参数,System.setProperty相当于一个静态变量,存在内存里面,使用el表达式和@value获取

 public static void main(String[] args) {
        System.setProperty("username", "张三");
        System.setProperty("age", "10");
 }

@Component
public class User {

    @Value("${user.user-name}")
    private String username;

    @Value("${user.age}")
    private String age;
    SetterAndGetter
        
    @Override
    public String toString() {
        return "User [username=" + username + ", age=" + age + "]";
    }
    
    User [username=张三, age=10]

2.配置文件自扫描

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
</bean>

熟悉的数据库配置。这里我们可以使用自动扫描

<!-- 配置文件 -->
    <context:property-placeholder location="classpath*:jdbc.properties" />

下面是jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true
username=root
password=root
#定义初始连接数
initialSize=5
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
  • 作者:令人智熄
  • 原文链接:https://blog.csdn.net/qq_38161409/article/details/88547596
    更新时间:2022-06-16 10:39:49