Implementing runtime value with Spring?

I tested spring-security for a sample web application. When declaring LDAPAuthenticationProvider, I noticed that you must declare all your settings in the applicationContext.xml!

As a newbie to spring, I understand that it would be necessary to declare dependencies in the applicationContext file. However, in a typical enterprise scenario, you must configure an administrator to configure your ldap settings. Thus, you will need to download the information associated with the ldap server from the database into your application, and then connect to the configured server. If this was a script, how do I do this in Spring?

+4
source share
1 answer

You can have properties in an external properties file in the form:

ldapUsername=value1 ldapPassword=value2 

And at the beginning of you applicationContext.xml put the following:

 <context:property-placeholder location="classpath:application.properties" /> 

then you can use them as follows:

 <bean id="someId" class="..."> <property name="ldapUsername" value="${ldapUsername}" /> <property name="ldapPassword" value="${ldapPassword}" /> </bean> 

Thus, your administrator will configure the properties in a simple application.properties file without having to view the applicationContext.xml complex

If you want them to be extracted from a source other than the properties file, you can extend the spring PropertyPlaceholderConfigurer and provide functionality for retrieving properties from the database.

This answer to a question similar to yours shows an example of how to implement this.

To update so that your values โ€‹โ€‹are entered at runtime, you will need to define your beans with a prototype scope. Otherwise, after creating the instance (with the initial settings), your beans will never change. However, this is a pretty big change for such simple effects. Therefore, I would suggest the following:

  • Create a (password protected) interface where the administrator can fill in his settings (or at least click on the โ€œI changed settingsโ€ button

  • when you click the button, update the settings / reload the settings from the database and set them to a singleton bean.

Since you are using spring -mvc, you can simply enter your bean into the spring controller and update the settings. How:

 public class MyController { @Autowired private LDAPAuthenticationProvider ldapProvider; public void saveSettings(..) { // get the new username and password first ldapProvider.setUsername(newUsername); ldapProvider.setPassword(newPassword); } } 

(if you don't want to use annotations, just use <property name="ldapProvider" ref="ldapProvider" /> in your controller definition)

LDAPAuthenticationProvider does not have setUsername and setPassword , so find how the credentials are set.

+7
source

Source: https://habr.com/ru/post/1301666/


All Articles