关于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或配置 }
相关推荐
编程星空25 分钟前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
程序员侠客行1 小时前
Spring事务原理 二
java·后端·spring
sjsjsbbsbsn2 小时前
Spring Boot定时任务原理
java·spring boot·后端
计算机毕设指导62 小时前
基于Springboot学生宿舍水电信息管理系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
计算机-秋大田2 小时前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
羊小猪~~4 小时前
MYSQL学习笔记(九):MYSQL表的“增删改查”
数据库·笔记·后端·sql·学习·mysql·考研
豌豆花下猫4 小时前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai
橘猫云计算机设计5 小时前
基于SSM的《计算机网络》题库管理系统(源码+lw+部署文档+讲解),源码可白嫖!
java·数据库·spring boot·后端·python·计算机网络·毕设
熬夜苦读学习5 小时前
Linux文件系统
linux·运维·服务器·开发语言·后端
坚定信念,勇往无前6 小时前
Spring Boot 如何保证接口安全
spring boot·后端·安全