Is it possible to specify the class name for Spring Framework in an external file?

I have an application built on the Spring Framework that uses an external properties file for some things, such as the database host string, username and password, so that we can check the configuration file in our repository (this is open source) and not compromise security db. This is also great, because developers can store their own copy of this file, and the application will automatically use the configuration on their system, rather than manually reconfiguring it.

I would like to be able to specify a bean in the same way. We are working with some classes that can change from developer to developer, and it would be great if we could let them specify this information in another file so that they would not have to communicate with the main configuration file.

To give you an idea, we have something like

<property name="url"> <value>${db.host}</value> </property> 

Where db.host is listed in another file. We want something like

 <bean name="ourBean" class="${class.weneed}" /> 

The above syntax does not actually work, but demonstrates what we want to do.

Thanks in advance!

Chris

+7
java spring
source share
3 answers

You can use FactoryBean . This example is a FactoryBean that takes advantage of Spring's ability to cast a class to a Class object when introducing properties:

 public class MyFactoryBean extends AbstractFactoryBean { private Class targetClass; public void setTargetClass(Class targetClass) { this.targetClass = targetClass; } @Override protected Object createInstance() throws Exception { return targetClass.newInstance(); } @Override public Class getObjectType() { return targetClass; } } 

And then:

 <bean name="ourBean" class="com.xyz.MyFactoryBean"> <property name="targetClass" value="${class.weneed}"/> </bean> 

The Spring context will now have a bean called ourBean , which is an object of type ${class.weneed}

+7
source share

another option would be to use a cocoon-spring-configurator , which is part of the Cocoon structure, but can be used on its own, without depending on any other cocoon objects.

we use this for many of our webapps. the general idea is to set up a bean factory based on runMode.

it makes it easy to replace / overwrite properties, but also override full bean fixes.

A common use case is to identify the beans that your application uses, and then add some additional configuration files (which are never checked in the source control) to override some beans to make fun of part of the application.

0
source share

I found that the bean created using reflection is not a valid spring bean (not registered in the spring context and no properties initialized), so here's a slight improvement:

 @Override protected Object createInstance() throws Exception { AutowireCapableBeabFactory beanFactory = (AutowireCapableBeabFactory ) getBeanFactory(); return beanFactory.createBean(this.targetClass); } 
0
source share

All Articles