关于spring字段注入的不同方式

1.@Vaule

在ssm的模式中

kotlin 复制代码
@Value("${jdbc.driver}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;

可以使用@value的方式直接注入字段,spring启动后,读取配置文件

其中:bootstrap.properties主要用于配置Spring Boot应用程序的启动阶段,而application.properties主要用于配置应用程序的业务逻辑。在实际开发中,我们通常会根据需要修改application.properties文件,而不需要修改bootstrap.properties文件。

当然,我们可以自定义资源的路径

less 复制代码
@Configuration
@PropertySource("classpath:jdbc.properties")
@Import({jdbcconfig.class})

在配置类里,通过@PropertySource来指定resource目录下的文件名,@PropertySource添加资源的路径

2.前缀的使用

前缀的自动注入注解由springboot提供

介绍一下在ssm的架构中,属性注入的两种方式

  1. @PropertySource:用于指定属性文件的位置,可以在Spring的配置类上使用。

  2. PropertyPlaceholderConfigurer:用于解析属性文件中的占位符,将属性值注入到Bean的属性中,比如:

    ini 复制代码
      <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:config.properties"/>
    </bean>
    <bean id="myBean" class="com.example.MyBean">
        <property name="someProperty" value="${property.key}"/>
    </bean>

    在这个例子中,,property.key是属性文件中的一个键,使用配置文件来注册bean

springboot提供了两个注解

@ConfigurationProperties(prefix = "myapp.database") ,当prefix+url与配置文件相同时,可自动注入 注意:这个bean对象需要写getter和setter方法

less 复制代码
@Component
@ConfigurationProperties(prefix = "myapp.database") 
public class DatabaseProperties { 
private String url; 
private String username; 
private String password; // 省略getter和setter方法 }

@EnableConfigurationProperties(DatabaseProperties.class) ,在

kotlin 复制代码
import org.springframework.boot.context.properties.EnableConfigurationProperties; 
import org.springframework.context.annotation.Configuration;
@Configuration 
@EnableConfigurationProperties(DatabaseProperties.class) 
public class AppConfig {
// 可以在这里注入其他Bean或配置 }
相关推荐
编码者卢布1 小时前
【Azure Storage Account】Azure Table Storage 跨区批量迁移方案
后端·python·flask
她说..3 小时前
策略模式+工厂模式实现审批流(面试问答版)
java·后端·spring·面试·springboot·策略模式·javaee
梦梦代码精4 小时前
开源、免费、可商用:BuildingAI一站式体验报告
开发语言·前端·数据结构·人工智能·后端·开源·知识图谱
李慕婉学姐5 小时前
【开题答辩过程】以《基于Spring Boot的疗养院理疗管理系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·spring boot·后端
tb_first5 小时前
SSM速通2
java·javascript·后端
一路向北⁢5 小时前
Spring Boot 3 整合 SSE (Server-Sent Events) 企业级最佳实践(一)
java·spring boot·后端·sse·通信
风象南5 小时前
JFR:Spring Boot 应用的性能诊断利器
java·spring boot·后端
爱吃山竹的大肚肚6 小时前
微服务间通过Feign传输文件,处理MultipartFile类型
java·spring boot·后端·spring cloud·微服务
毕设源码-邱学长7 小时前
【开题答辩全过程】以 基于Springboot的酒店住宿信息管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
咖啡啡不加糖8 小时前
Grafana 监控服务指标使用指南:打造可视化监控体系
java·后端·grafana