当前位置: 首页 > 面试题库 >

spring-boot属性注入在自定义@Configuration类中不起作用

帅银龙
2023-03-14
问题内容

我想制作一个DatabaseConfig类来设置与数据库相关的东西(EntityManager,DataSource,TransactionManager)并获取我@Value("${property.name}")String字段上使用的属性

喜欢

@Configuration
public class DataBaseConfig {
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;
    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;
    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;
    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;
    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

// All my @Beans
}

问题是,所有这些字符串都是NULL,而不是我的属性文件的值。

如果我将代码放入我的Application类(具有main和中引用的代码SpringApplication.run(Application.class, args);),则值注入有效

简而言之,@Value在我的Application类中有效,但在我的自定义@Configuration类中无效:(

有什么事吗 还是需要更多信息?

更新 :更多代码

我的Application.java中的方式1,DB
Config和@Value使用和不使用PropertySourcesPlaceholderConfigurer

import java.beans.PropertyVetoException;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class)
public class Application {
    public static void main(String[] args) throws Throwable {
        SpringApplication.run(Application.class, args);
    }

    // @Bean
    // public static PropertySourcesPlaceholderConfigurer properties() {
    // PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    // pspc.setLocations(new Resource[] { new ClassPathResource("application.properties") });
    // return pspc;
    // }

    /*****************************/
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;

    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;

    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;

    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;

    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform(hibernateDialect);
        boolean generateDdl = Boolean.parseBoolean(hibernateGenerateDdl);
        boolean showSql = Boolean.parseBoolean(hibernateShowSql);
        vendorAdapter.setGenerateDdl(generateDdl);
        vendorAdapter.setShowSql(showSql);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setDataSource(dataSource());
        factory.setPackagesToScan("xxx");

        return factory;
    }

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(hibernateConnectionUsername);
        dataSource.setPassword(hibernateConnectionPassword);
        try {
            dataSource.setDriverClass(hibernateConnectionDriverClass);
        } catch (PropertyVetoException e) {
            throw new IllegalArgumentException("Wrong driver class");
        }

        dataSource.setJdbcUrl(hibernateConnectionUrl);
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

方法2(我想要的),在自己的文件(DatabaseConfing.java)中的DB
Stuff不适用于我拥有PropertySourcesPlaceholderConfigurer(Application或DatabaseConfig)的位置,因为它总是在DatabaseConfig内部@Beans之后被称为:(

import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import com.mchange.v2.c3p0.ComboPooledDataSource;


@Configuration
public class DatabaseConfig {
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;
    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;
    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;
    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;
    @Value("${hibernate.dialect")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

        // @Bean
        // public static PropertySourcesPlaceholderConfigurer properties() {
        // PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        // pspc.setLocations(new Resource[] { new ClassPathResource("application.properties") });
        // return pspc;
        // }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform(hibernateDialect);
        boolean generateDdl = Boolean.parseBoolean(hibernateGenerateDdl);
        boolean showSql = Boolean.parseBoolean(hibernateShowSql);
        vendorAdapter.setGenerateDdl(generateDdl);
        vendorAdapter.setShowSql(showSql);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setDataSource(dataSource());
        factory.setPackagesToScan("xxx");

        return factory;
    }

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(hibernateConnectionUsername);
        dataSource.setPassword(hibernateConnectionPassword);
        try {
            dataSource.setDriverClass(hibernateConnectionDriverClass);
        } catch (PropertyVetoException e) {
            throw new IllegalArgumentException("Wrong driver class");
        }
        System.err.println(hibernateConnectionUrl);
        dataSource.setJdbcUrl(hibernateConnectionUrl);
        return dataSource;
    }
}

问题答案:

而不是DatabaseConfig将以下内容添加application.propertiessrc/main/resources(从而删除您的DatabaseConfig类)

#DataSource configuration
spring.datasource.driverClassName=<hibernateConnectionDriverClass>
spring.datasource.url=<hibernateConnectionUrl>
spring.datasource.username=<hibernateConnectionUsername>
spring.datasource.password=<hibernateConnectionPassword>

#JPA/HIbernate
spring.jpa.database-platform=<dialect-class>
spring.jpa.generate-ddl=<hibernateGenerateDdl>
spring.jpa.show-sql=<hibernateShowSql>

< placeholder>替换为实际值,并且spring-boot会解决这个问题。

提示删除C3P0依赖项,因为Spring将为您(默认)提供tomcat连接池(这是更新的,并且更加活跃地维护,尽管该名称在Tomcat外部/外部完全可用)。



 类似资料:
  • 我成功地注入了Gradle项目。应用程序。yml,然后将其注入服务应用程序。我的申请。yml看起来像这样: 但只有当我从cli启动应用程序时,它才有效: 如果我尝试从IntelliJ启动应用程序,它不起作用,并且失败了: 我阅读了Stackoverflow的所有答案,他们提出了两种解决方案: > 使用Spring轮廓 修改运行配置并在启动 gradle 任务之前运行:流程资源 当我从Intelli

  • 我创建了一个新的注释来验证控制器上的参数: 这是我的验证器: 这是我的控制器: 我的控制器注释为: 我还有一个建议控制器,我打算用它来捕捉抛出的异常: 我在控制台上得到的是: pom.xml中的依赖关系: 谁能告诉我我错过了什么?

  • 我做了一个名为AcessoCliente的单例类 但我需要对我的单例类执行一个名为ValidadorNivelDeAcessoBusiness的类的依赖注入

  • 问题内容: 我在Tomcat 8.0.33和Spring Boot Starter Web上,并将其保存在我的setenv.sh中 在覆盖文件夹中,我有2个文件 1) 2) application.properties中有一个条目 我看到正确的log.level被输入到我的代码中,这意味着该命令正在运行。只是我不知道为什么我的超控未按预期发生 我的工作区中没有任何`PropertyPlacehol

  • 我将尽量忽略其他细节,并将其简短化: 当在Spring中进行验证时(Spring MVC或使用注入

  • 自定义注释 自定义注释处理程序 超级类 子类 Subclass调用SuperClass方法但在不调用 当我将移动到子类method时,AspectHandler可以获取 如何在超类保护方法中使用自定义注释? 更改 但还是不行 所以我把我的< code >子DAO改成了under code 这不是完美的解决方案,但它的工作原理 情况1:从子类方法调用超类方法不起作用 情况 2:使超级类实例和从实例调