2

I have a web application which runs fine using embedded Tomcat server. What I need to do is to have a Tomcat server (not embedded) that has all the information about DB connection so that my app could connect this DB by means of JNDI. I followed this tutorial (except for Hibernate part cause I don't use it rn): https://www.baeldung.com/spring-persistence-jpa-jndi-datasource but I fail to run my app cause of NoInitialContextException (Need to specify class name in environment or system property, or in an application resource file: java.naming.factory.initial). My code:

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:persistence-jndi.properties")
public class PersistenceJNDIConfig {
    @Autowired
    private Environment env;
    @Bean
    public DataSource dataSource() throws NamingException {
        return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
    }
}

.properties file:

jdbc.url=java:comp/env/jdbc/postgres

server.xml in tomcat dir:

 <Resource name="jdbc/postgres" 
  auth="Container"
  type="javax.sql.DataSource" 
  driverClassName="org.postgresql.Driver"
  url="jdbc:postgresql://localhost:5432/university"
  username="admin" 
  password="admin" 
  maxTotal="20" 
  maxIdle="10" 
  maxWaitMillis="-1"/>

context.xml

  <ResourceLink 
    name="jdbc/postgres" 
    global="jdbc/postgres" 
    type="javax.sql.DataSource"/>

Any suggestions on how to solve this problem are much appreciated.

  • I believe your solution is here: https://stackoverflow.com/questions/24941829/how-to-create-jndi-context-in-spring-boot-with-embedded-tomcat-container – Luis Antonio Apr 29 '21 at 12:17
  • Will it work if I want to use Tomcat server that I've just installed myself? Not the default spring tomcat. – GrigoryKrasovsky Apr 29 '21 at 12:26
  • See this solution with tomcat external: https://stackoverflow.com/questions/64076682/configure-datasource-using-jndi-using-external-tomcat-9-server-spring-boot – Luis Antonio Apr 29 '21 at 12:45
  • Can you add the complete stack trace of the error? Are you sure you don't start the server with the `-nonaming` option? – Piotr P. Karwasz Apr 29 '21 at 19:23

0 Answers0