为了账号安全,请及时绑定邮箱和手机立即绑定

执行@Bean注解方法时自动装配环境变量为NULL

执行@Bean注解方法时自动装配环境变量为NULL

汪汪一只猫 2023-09-27 21:20:07
我试图通过自动装配环境变量来检索从 .yml 文件加载的属性,但出现空指针异常:Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/example/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException我想以编程方式创建一个 DataSource bean,同时将详细信息(用户名、密码、主机等)保留在配置文件中。这是我目前的设置:@SpringBootApplication@ImportResource({"classpath:controllers.xml"})public class WebApplication{  public static void main(String[] args){    SpringApplication.run(WebApplication.class, args);  }}server:  port: 8080database:  host: localhost  instance: db_instance  port: 3036  user: root  password: passkey@Configurationpublic class AppConfig {  @Autowired  private Environment environment;  @Bean  public DataSource dataSource() {    String url = "jdbc:mysql://" +        environment.getProperty("database.host") +        ":" + environment.getProperty("database.port") +        "/" + environment.getProperty("database.instance") +        "?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";    return DataSourceBuilder.create()        .driverClassName("com.mysql.jdbc.Driver")        .url(url)        .username(environment.getProperty("database.user"))        .password(environment.getProperty("database.password"))        .build();  }}我不偏爱 .yml 文件格式或使用环境变量。如果有不同/更好的方法来从 .yml 文件(或其他文件格式)获取数据,我愿意尝试。
查看完整描述

2 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

有很多方法可以做到这一点。

  1. 由于您使用的是 Springboot,因此不必像这样显式创建数据源(如果这样做,您将错过 springboot 的主要功能之一)。如果你用右键在properties/yml中声明参数,Springboot会自动为你配置这个。
    搜索spring.datasource......

  2. 如果您希望自己执行此操作,那么您可以使用以下命令将properties/yml文件中的所有变量自动装配到Bean中, ConfigurationProperties然后在bean创建方法中使用该bean作为方法参数。

  3. 在您的 AppConfig 类中使用@Value{}并在您的数据源创建方法中使用它。


查看完整回答
反对 回复 2023-09-27
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

不太确定controllers.xml 中有什么。但我能够获取环境变量并使用它。

我将您在 application.yml 中提到的属性放置在 /src/main/resources 中

我使用 Spring boot-2.1.9 版本使其工作,下面是我的 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.sample</groupId>

    <artifactId>stackoverflow</artifactId>

    <version>0.0.1</version>

    <packaging>jar</packaging>


    <name>stackoverflow</name>

    <description>stackoverflow</description>


    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.1.9.RELEASE</version>

        <relativePath /> <!-- lookup parent from repository -->

    </parent>


    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <java.version>1.8</java.version>

    </properties>


    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter</artifactId>

        </dependency>


        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>


        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>


        </dependency>




        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>


        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

        </dependency>

    </dependencies>


    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>


    <repositories>

        <repository>

            <id>spring-snapshots</id>

            <name>Spring Snapshots</name>

            <url>https://repo.spring.io/libs-snapshot-local</url>

            <snapshots>

                <enabled>true</enabled>

            </snapshots>

        </repository>

        <repository>

            <id>ojo-snapshots</id>

            <name>OJO Snapshots</name>

            <url>https://oss.jfrog.org/artifactory/libs-snapshot</url>

            <snapshots>

                <enabled>true</enabled>

            </snapshots>

        </repository>

    </repositories>



</project>


查看完整回答
反对 回复 2023-09-27
  • 2 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信