Springboot属性注入

it2022-05-05  149

SpringBoot属性注入

1.@Autowired①使用@ConfigurationProperties注解报错②代码---@Autowired自动注入 2.构造方法注入3.@Bean方法形参注入4.直接在@Bean方法上使用@ConfigurationProperties(prefix="jdbc")

1.@Autowired

①使用@ConfigurationProperties注解报错

Not registered via @EnableConfigurationProperties or marked as Spring component less... (Ctrl+F1) Inspection info: Verifies @ConfigurationProperties setup. New in 2018.3

解决办法 1.在属性类上添加注解@Component 2.在配置类的@EnableConfigurationProperties注解中添加值 使用@ConfigurationProperties注解应在配置类中添加@EnableConfigurationProperties启用注入属性

②代码—@Autowired自动注入

application.properties JdbcProperties JdbcConfiguration HelloController pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.qry.springboot</groupId> <artifactId>springboot</artifactId> <version>1.0.0-SNAPSHOT</version> <!-- 所有的springboot应用都要以该工程为父工程 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <!-- 启动器:每个启动器背后都是一堆的依赖。web启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- 数据库MySQL驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- jpa依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> </project>

2.构造方法注入

其他的类不变,只改变JdbcConfiguration类的内容

3.@Bean方法形参注入

其他的类不变,只改变JdbcConfiguration类的内容

4.直接在@Bean方法上使用@ConfigurationProperties(prefix=“jdbc”)

这个属性注入不需要JdbcProperties类,只需要在JdbcConfiguration类的方法上添加注解即可


最新回复(0)