使用 spring 和 Java 将数据库配置存储在 application.properties 中

问题描述 投票:0回答:1

我编写了一个使用多个数据库连接的应用程序。我创建了一个必须包含连接信息的地图。连接值存储在文件 application.properties 中。

文件 application.properties 存储在文件夹 /src/main/resources 中

文件 application.properties 包含以下信息:

datasource1.database = mydatabase
datasource1.database = mydatabase
datasource1.user = efe
datasource1.password = efe

datasource2.database = security
datasource2.user = scott
datasource2.password = tiger

我尝试使用函数 org.springframework.core.env.Environment.getProperty 填写管理这些信息的类的属性。这是我的课:

package com.sharex19.sswfe.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:application.properties")
public class PostgresConnector extends DatabaseConnector {
    
    @Autowired
    private Environment env;

    private static final Logger log = LogManager.getLogger(PostgresConnector.class);
            
    private static PostgresConnector instance=null;
    private static Connection c=null;
    private static HashMap<String,Datasource> cc;
    
    private static String database1;
    private static String user1;
    private static String password1;
    
    private static String database2;
    private static String user2;
    private static String password2;
    
    
    public PostgresConnector() {
        
        System.out.println("CREATION DES COLLECTIONS DE CONNECTIONS");
        
        String database1 = env.getProperty("datasource1.database");
        String user1 = env.getProperty("datasource1.user");
        String password1 = env.getProperty("datasource1.password");
        
        String database2 = env.getProperty("datasource2.database");
        String user2 = env.getProperty("datasource2.user");
        String password2 = env.getProperty("datasource2.password");
        
        
        System.out.println("ACCES A DATABASE1...");
        
        if ( database1 == null ) {
            System.out.println("DATABASE 1 IS NULL");       
        } else {
            System.out.println("DATABASE1:".concat(database1));
        }
        
        System.out.println("DATABASE1:".concat(user1).concat(password1));
        
        System.out.println("ACCES A DATABASE2...");
        
        System.out.println("DATABASE2:".concat(user2).concat(password2));
        
        cc = new HashMap();
        
        cc.put(database1,new Datasource(user1,password1));
        cc.put(database2,new Datasource(user2,password2));
        
    }
    
    public static Connection getInstance(String databasename){
        log.info("APPEL PostgresConnector.getInstance()");
        if (instance==null) {
            instance = new PostgresConnector();
            c=PostgresConnector.connect(databasename,
                cc.get(databasename).user,
                cc.get(databasename).password);
        }
        return  c;
    }
    
    public static Connection connect(String databasename, 
        String user, String password) {
        
        System.out.println("database:".concat(databasename));
        System.out.println("user:".concat(user));
        System.out.println("password:".concat(password));
        
          Connection c = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/".
                concat(databasename),
                    user, password);
          } catch (Exception e) {
             e.printStackTrace();
             System.err.println(e.getClass().getName()+": "+e.getMessage());
             System.exit(0);
          }
          System.out.println("Opened database successfully");
          return c;
       }
}

我获得以下信息错误:

juil. 17, 2024 9:49:23 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Le Servlet [SecureSpringWebFlow50] dans l'application web [/SSA19] a retourné une exception lors de son chargement
java.lang.NullPointerException: Cannot invoke "org.springframework.core.env.Environment.getProperty(String)" because "this.env" is null
    at com.sharex19.sswfe.utils.PostgresConnector.<init>(PostgresConnector.java:52)
    at com.sharex19.sswfe.utils.PostgresConnector$$EnhancerBySpringCGLIB$$b5f344d4.<init>(<generated>)
    at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1326)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1232)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:921)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:716)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:591)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1164)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1117)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4957)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5264)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:265)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:476)

我还尝试使用注释 @Value(${...}) 来执行此操作。

你能帮我吗?我提前谢谢你了。

java spring database configuration application.properties
1个回答
0
投票

@Autowired
在构造函数之后加载,所以如果你想在构造函数中获取属性,你必须传递Environment作为参数,或者创建一个新函数并用
@PostConstruct
注释,然后你可以在函数中初始化静态字段。

© www.soinside.com 2019 - 2024. All rights reserved.