How can I inject a Class of an object, not an object itself - spring

I'm trying to inject a list of Class. I want a list of classes, not objects.
My class looks like this:
public class CodeServiceImpl{
private List<Class<?>> codeList;
// getter and setter
My spring configuration file (I'm not using annotations but xml) is
<bean id="myCodeServiceImpl" class = "net.croz.service.CodeServiceImpl">
<property name="codeList">
<list>
<ref bean="myAddress"/>
<ref bean="myCity"/>
<ref bean="myCountry"/>
</list>
</property>
</bean>
<bean id="myAddress" class="java.lang.Class" factory-method="forName">
<constructor-arg value="net.croz.model.Address"/>
</bean>
<bean id="myCity" class="java.lang.Class" factory-method="forName">
<constructor-arg value="net.croz.model.City"/>
</bean>
<bean id="myCountry" class="java.lang.Class" factory-method="forName">
<constructor-arg value="net.croz.model.Country"/>
</bean>
But the list codeList isn't being populated. It ends up being a null object. Thank you for your help.

Actually it works as is:
<bean class="com.my.proj.Foo">
<constructor-arg value="java.lang.String, org.springframework.util.StringUtils, byte[]"/>
</bean>
where Foo is:
public class Foo {
private final List<Class<?>> codeList;
public Foo(Class<?>... codeList) {
this.codeList = Arrays.asList(codeList);
}
}
The ConversionService does the stuff for converting comma-separated string to the Class<?>[] and tries to resolve each class on its own using BeanClassLoader

Related

Spring Beans: Call a specific class method after instantiation

I have 2 classes A & B. Booth are from some 3rd party package.
I have something like this in code
A objA = new objA;
objA.registerModule(new B());
Now I was thinking of #Autowiring A in the code. Is there a way to create a bean of A and B and call registerModule of class A & pass in reference to B in its bean?
Something like this:
<bean id="classB" class = ... />
<bean id="classA>
/*pass in reference to B */
</bean>
Yes there is, take a look at: MethodInvokingFactoryBean
In your case it should be something like this:
<bean id="classB" class = "com.company.B"/>
<bean id="classA" class = "com.company.A"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="classA"/>
<property name="targetMethod" value="registerModule"/>
<property name="arguments">
<list>classB</list>
</property>
</bean>

Spring bean definition null reference

public class A{
private B b;
}
public class B{
}
applicationContext.xml
<bean id="aBean" class="A">
<property name="b"> ??? </property>
</bean>
How to create an instance of A with b = null when using context.getBean("aBean")?
I have tried <property name="b"><null/></property>, but this doesn't work.
Actually it will be null by default. No need for specific configuration, i.e. just omit <property> element.
And actually
<bean id="aBean" class="A">
<property name="b"><null /></property>
</bean>
should work: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-null-element
Huh? Just don't do anything.
<bean id="aBean" class="A"/>
In Java object references are null by default.

customizing spring 3 mvc:annotation for RequestMappingHandlerMapping

I am using <mvc:annotation-driven/> and I would like to configure RequestMappingHandlerMapping for disabling useTrailingSlashMatch. When I declare another RequestMappingHandlerMapping, I will end up 2 RequestMappingHandlerMapping. How can I configure RequestMappingHandlerMapping ?
As you have already noted, this is feasible in xml by removing mvc:annotation-driven and replacing with the entire xml equivalent:
<bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"></property>
<property name="validator">
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</property>
</bean>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
</list>
</property>
</bean>
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useTrailingSlashMatch" value="true"></property>
</bean>
Can you try with Java config to override RequestMappingHandlerMapping value
#Configuration
#ComponentScan(basePackages = "base.package.name")
public class WebAppConfig extends WebMvcConfigurationSupport {
#Override
#Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping rmh = super.requestMappingHandlerMapping();
rmh.setUseTrailingSlashMatch(false);
return rmh;
}
}
If you want a solution that doesn't involve duplicating functionality in Spring then you can override the DisplatcherServlet. in Servlet 3.0 container this might look like:
#WebServlet(name="spring-dispatcher", loadOnStartup=1, urlPatterns={"/"},
initParams={
#WebInitParam(name="contextConfigLocation",
value="/WEB-INF/spring/spring-dispatcher-servlet.xml")})
public class MyDispatcherServlet extends DispatcherServlet {
#Override
protected void initStrategies(ApplicationContext context) {
super.initStrategies(context);
for (RequestMappingInfoHandlerMapping handlerMapping
: BeanFactoryUtils.beansOfTypeIncludingAncestors(
context, RequestMappingInfoHandlerMapping.class, true, false).values()) {
handlerMapping.setUseTrailingSlashMatch(false);
}
}
}
Add the following to your spring configuration file to toggle the useTrailingSlashMatch field.
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useTrailingSlashMatch" value="true">
</property>
</bean>

Spring #PersistenceContext how to inject manually the entity manager in my GenericDao

Hallo all:
I read the spring reference about this point.
I would choose to use the #PersistenceContext in my DAO to inject a shared transactional entity manager, but since I use the GenericDaoJpaImpl pattern over two entityManagerFactories that point to 2 different persistence units I cannot use it.
So right now in my application I have this configuration:
entityManagerFactoryies:
<bean id="entityManagerFactoryIban0" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/contratto-persistence-iban0.xml" />
</bean>
<bean id="entityManagerFactoryCont0" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/contratto-persistence-cont0.xml" />
</bean>
<bean abstract="true" id="abstractDaoJpaImplIban0" lazy-init="false">
<property name="entityManagerFactory" ref="entityManagerFactoryIban0" />
</bean>
<bean abstract="true" id="abstractDaoJpaImplCont0" lazy-init="false">
<property name="entityManagerFactory" ref="entityManagerFactoryCont0" />
</bean>
Then each of my DAOs is an instance of the GenericDaoImpl:
#Repository
public class GenericDaoJpaImpl<T, ID extends Serializable> implements GenericDao<T, ID> {
private Class<T> entityClass;
private EntityManagerFactory entityManagerFactory;
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public GenericDaoJpaImpl() {
super();
}
public GenericDaoJpaImpl(Class<T> entityClass) {
super();
this.entityClass = entityClass;
}
/**
* #see it.alten.intesasanpaolo.contratto.dao.common.GenericDao#getItemByID(java.io.Serializable)
*/
#Override
public T getItemByID(ID id) {
EntityManager em = entityManagerFactory.createEntityManager();
return em.find(entityClass, id);
}
I construct my dao via spring in this way:
<bean id="eventMessageDao" parent="abstractDaoJpaImplCont0" class="it.alten.intesasanpaolo.contratto.dao.common.GenericDaoJpaImpl">
<constructor-arg>
<value>it.alten.intesasanpaolo.contratto.domain.event.OnlineEventMessage</value>
</constructor-arg>
</bean>
Now I would like to modify the GenericDaoJpaImpl as described in the spring documentation not to be associated to the entityManagerFactory from which I have to create every time the entityManager but directly to the entityManager.
I would like to define it in the context in a way I can inject it to the correct abstract dao to be extended from every dao.
<bean abstract="true" id="abstractDaoJpaImplIban0" lazy-init="false">
<property name="entityManagerFactory" ref="entityManagerFactoryIban0" />
</bean>
How can I achieve this?
kind regards
Massimo
You can use SharedEntityManagerBean to construct a transactional EntityManager from the EntityManagerFactory:
<bean id="entityManagerFactoryIban0"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
</bean>
<bean id="entityManagerIban0"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactoryIban0" />
</bean>
<bean abstract="true" id="abstractDaoJpaImplIban0" lazy-init="false">
<property name="entityManager" ref="entityManagerIban0" />
</bean>
You can provide the persistence unit name in the xml configuration, using the SharedEntityManagerBean, like below:
<bean id="testDao" class="com.test.persistence.dao.BaseDAO">
<property name="entityManager">
<bean class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="persistenceUnitName" value="persistence-test-unit" />
</bean>
</property>
</bean>
of course, you can have the SharedEntityManagerBean as a separate bean
Here, I m injecting entityManager into BaseDAO as you're doing using #PersistenceContext(unitName="...")

Reading a list from a file .properties using Spring properties place holder

I want to fill a bean list property using Spring properties place holder.
Context file
<bean name="XXX" class="XX.YY.Z">
<property name="urlList">
<value>${prop.list}</value>
</property>
</bean>
Properties File
prop.list.one=foo
prop.list.two=bar
Any help would be much appreciated
Use a util:properties element to load your properties. You can use PropertyPlaceholderConfigurer to specify the path to your file:
<bean name="XXX" class="XX.YY.Z">
<property name="urlList">
<util:properties location="${path.to.properties.file}"/>
</property>
</bean>
Update I've misunderstood the question; you only want to return properties where key starts with specific string. The easiest way to achieve that would be to do so within setter method of your bean. You'll have to pass the string to your bean as a separate property. Extending the above declaration:
<bean name="XXX" class="XX.YY.Z" init-method="init">
<property name="propertiesHolder">
<!-- not sure if location has to be customizable here; set it directly if needed -->
<util:properties location="${path.to.properties.file}"/>
</property>
<property name="propertyFilter" value="${property.filter}" />
</bean>
In your XX.YY.Z bean:
private String propertyFilter;
private Properties propertiesHolder;
private List<String> urlList;
// add setter methods for propertyFilter / propertiesHolder
// initialization callback
public void init() {
urlList = new ArrayList<String>();
for (Enumeration en = this.propertiesHolder.keys(); en.hasMoreElements(); ) {
String key = (String) en.nextElement();
if (key.startsWith(this.propertyFilter + ".") { // or whatever condition you want to check
this.urlList.add(this.propertiesHolder.getProperty(key));
}
} // for
}
If you need to do this in many different places you can wrap the above functionality into a FactoryBean.
A simpler solution:
class Z {
private List<String> urlList;
// add setters and getters
}
your bean definition
<bean name="XXX" class="XX.YY.Z">
<property name="urlList" value="#{'${prop.list}'.split(',')}"/>
</bean>
Then in your property file:
prop.list=a,b,c,d
<bean id="cpaContextSource" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="urls">
<bean class="org.springframework.util.CollectionUtils" factory-method="arrayToList">
<constructor-arg type="java.lang.Object">
<bean class="org.springframework.util.StringUtils" factory-method="tokenizeToStringArray">
<constructor-arg type="java.lang.String" value="${myList}"/>
<constructor-arg type="java.lang.String" value=" "/>
</bean>
</constructor-arg>
</bean>
</property>
where:
myList=http://aaa http://bbb http://ccc
The only way i see here is, implement the interface 'MessageSourceAware' to get the messageResource, and then manually populate your list.
class MyMessageSourceAwareClass implemets MessageSourceAware{
public static MessageSource messageSource = null;
public void setMessageSource(MessageSource _messageSource) {
messageSource = _messageSource;
}
public static String getMessage( String code){
return messageSource.getMessage(code, null, null );
}
}
--- Properties File ---
prop.list=foo;bar;one more
Populate your list like this
String strlist = MyMessageSourceAwareClass.getMessage ( "prop.list" );
if ( StringUtilities.isNotEmptyString ( strlist ) ){
String[] arrStr = strList.split(";");
myBean.setList ( Arrays.asList ( arrStr ) );
}
Just add the following Bean definition
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:myprops.properties</value>
</list>
</property>
</bean>
To use it like so please note port is defined in myprops.properties
<bean id="mybean" class="com.mycompany.Class" init-method="start">
<property name="portNumber" value="${port}"/>
</bean>
There are several ways , one of them is below.
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);

Resources