Spring Boot - JNDI value lookup

别等时光非礼了梦想. 提交于 2019-12-06 21:05:52

There is a way to access test/value... Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your InitialContext (until the env vars have been setup).

To achieve this, I used Spring's @Lazy annotation. e.g.

SampleTomcatJndiApplication.java

import javax.naming.*;

@Bean
@Lazy
public Context environmentContext() throws NamingException {
    Context ctx = new InitialContext();
    Context envCtx = (Context) ctx.lookup("java:comp/env");
    return envCtx;
}

SomeOtherComponent.java

@Lazy
@Autowired
private Context environmentContext;

public String getTestValue() throws NamingException {
    return environmentContext.lookup("test/value").toString();
}

Not sure if this violates any "best practices" - perhaps Spring has a better way of retrieving JNDI variables?? Not sure what the implications are if the JNDI var is changed on the server side (whether the value is re-looked-up)?? If anyone knows, please post back here!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!