Store database configuration in application.properties with spring and Java

I am writing an application that uses several connections to several databases. I created a Map that must contain the connection information. The connections values are stored in the file application.properties.

The file application.properties is stored in the folder /src/main/resources.

The file application.properties contains the following information:

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

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

I tried to use the function ozrg.springframework.core.env.Environment.getPropertyz
to fill in the attributes of a Class that manages this information.

This is my class:

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;
       }
}

I obtain the following information errors:

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)

I tried also to use the annotation @Value(${...}) to do this.

2

As you can see

java.lang.NullPointerException: Cannot invoke “org.springframework.core.env.Environment.getProperty(String)” because “this.env” is null

It clearly says that env is null.

@Autowired loads after the constructor, so if you want to get the property in the constructor, you must pass the Environment as a parameter.

public PostgresConnector(Environment env) {
    ...
}

or create a new function and annotate it with @PostConstruct. Then you can initialise a static field in the function.

@PostConstruct
public init() {
    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");
    
    ...
}

New contributor

Engine Chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật