I need 2 endpoint mapping beans with the same id - java

let's say my app has a feature which can be enabled or disabled:
if disabled, spring beans (including endpoint mappings) will be loaded from main.xml
if enabled, spring beans (including endpoint mappings) will be loaded from main.xml and extra.xml.
The problem is my endpoint mapping has an id of "mynamespaceEndpointMapping". This bean is of the type org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping.
How do i define this bean in such a way that when it's loaded from main.xml it has only one endpoint but when it's loaded from extra.xml it has 10 endpoints? (I don't want all the 10 endpoints defined in main.xml if i have no use for them there) I could use bean inheritance but this would break the namespace naming convention since i would probably need different ids for the beans...
Thanks,
Teo

You need to override the spring bean. Like in this answer: Spring's overriding bean
But this is only possible with XML configuration and not with annotations.
EDIT: I meant the accepted answer. But I tested it with my own code.
I got 2 id's. In test1.xml
<bean id="test" class="Test1" />
and in test2.xml
<bean id="test" class="Test2" />
During startup is use both "test1.xml", "test2.xml" (in that order) in the ApplicationContext en when I get the Spring bean test it's of class Test2.

Related

Spring Security, multiple http elements. Which is which?

I have a Spring Config which is working fine. My Spring Config uses multiple security:http sections.
When you define a security:http section, certain operations happen automagically, such as some bean definitions. One of these beans that get defined automatically, is a SessionAuthenticationStrategy -implementing bean.
Question: how can you identify which is which? For example I need to reference from code, via #Autowired, a specific authentication strategy, defined in a specific http:security tag; how can I accomplish this?
One way to have the same SessionAuthenticationStrategy instance in your custom bean and inside <sec:http>-spawned machinery is to go in the opposite direction: define SessionAuthenticationStrategy explicitly and inject it wherever you want, including http configuration:
<bean id="fancySessionAuthStrategy" class="com.fancy.FancySessionAuthStrategy">
...
</bean>
<sec:http ...>
<sec:session-management session-authentication-strategy-ref="fancySessionAuthStrategy"/>
...
</sec:http>
The only problem here is that you will have to manually build that strategy bean definition.
An example can be found in the documentation: http://docs.spring.io/spring-security/site/docs/current/reference/html/session-mgmt.html

Spring without getBean(..)

I'm trying to get a better understanding of the #Autowired annotations component scanning, but all the examples I found so far use context.getBean(..) at some point to get at least one Bean to start with.
I also read that doing that is considered bad practice , but I can't seem to find any information on how to do it without context.getBean(..)
Could somebody please enlighten me with an example and information on how to do this ?
Define your bean in xml and use
<context:component-scan base-package="com" />
<mvc:annotation-driven />
Bean def
<bean id="processEngine" class="com.processEngine">
<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>
now you can get bean as following
#Autowired
private ProcessEngine processEngine;
how it works
spring scans the bean's recipes either from xml or java configuration. then spring creates a beanDefinitions which are 'loaded' into BeanFactory. BeanFactory triggers a set of BeanPostProcessors (BPP) which are scanning classes for particular annotations like Autowired/Resource/PostProcessor and etc. and do appropriate actions. in case when your class contains #Autowired annotation, AutowiredAnnotationBeanPostProcessor would auto wire required field (dependencies), and when creation of an object is done and all BPP worked out, object is ready to be used by the app, from this point your code can get 'ready' objects from container.
there are some cases when you would need to access this beans from the code which is out of spring's control and not managed by container. in order to do so, you would need to get the ApplicationContext (container) and call #getBean specifying either name or type. using applicationContext directly is not a good practice because there are some problems that you can come to, f.ex. id of a bean might be changed and if you refer to bean by id then NPE would be thrown.
configuration
there are several approaches to configure spring to scan the classes for finding bean recipes. one would be defining component-scan, in this case classes which are located in the path that you've set and having any of valid spring annotations like #Component, #Service, #Repository, #Controller (for web container) would be considered. another way would be specifying each bean separately using <bean> or #Bean.
examples.
if you want to create a web app then you should see DispatcherServlet with ContextLoaderListener classes. this classes would boot your app and load everything according to configuration. f.ex. here,
but if you want to create a desktop app, then you would end up with something like this
From time to time (usually when not using Spring Boot), I use something along the lines of the following code:
public static <T> T autowire(ApplicationContext ctx, T bean) {
ctx.getAutowireCapableBeanFactory().autowireBean(bean);
return bean;
}
In my main, I create an instance of the main application class that contains a few #Autowired annotations for the main services / entry points to my Spring application.

Spring: Xml based Autowiring a list of beans by interface type

With Spring it is possible to inject a list of beans by the interface class like:
#Component
public class Service {
#Autowire
private List<InterfaceType> implementingBeans;
...
}
All defined beans that implement this interface will be present in this List.
The annotation based approach is not possible for me, as the Service class is in a module that must not have spring dependencies.
I need to use this mechanism from outside via xml configuration.
<bean id="service" class="...Service">
<property name="implementingBeans">
??? tell spring to create a list bean that resolves all beans of the interfaceType.
</property>
</bean>
Does anyone know how to solve this?
EDIT: Additionally, there are more than one spring applications that use this service. So the best solution would be to handle this szenario completely via xml configuration. I can then copy the xml parts to all spriong applications that need this.
I want to avoid having a kind of initializer bean that gets the service injected and must then be copied to all spring applications.
Kind regards.
An XML-only solution would simply have you declare a <bean> of the "external" type and provide an autowire value of "byType".
Controls whether bean properties are "autowired". This is an
automagical process in which bean references don't need to be coded
explicitly in the XML bean definition file, but rather the Spring
container works out dependencies.
[...]
"byType" Autowiring if there is exactly one bean of the property type in the container. If there is more than one, a fatal error is
raised, and you cannot use byType autowiring for that bean. If there
is none, nothing special happens.
The explanation is a little confusing in that we expect multiple InterfaceType beans, but the actual field is of type List and Spring will be able to dynamically instantiate one and add all the InterfaceType beans to it, then inject it.
Your XML would simply look like
<bean id="service" class="...Service" autowire="byType">
</bean>
My original suggested solution made use of SpEL.
In the module that does have Spring dependencies, create a DTO
#Component(value = "beanDTO")
public class BeanDTO {
#Autowire
private List<InterfaceType> implementingBeans;
public List<InterfaceType> getImplementingBeans() {
return implementingBeans;
}
}
and then use SpEL to retrieve the value of implementingBeans from the beanDTO bean.
<bean id="service" depends-on="beanDTO" class="...Service">
<property name="implementingBeans" value="{beanDTO.implementingBeans}" />
</bean>
Spring will create the BeanTDO bean, inject all the beans that are of type InterfaceType. It will then create the service bean and set its property from beanDTO's implementingBeans property.
Following comments on question:
In an effort to be more JSR 330 compliant, Spring has introduced support for Java EE's javax.inject package. You can now annotate your injection targets with #javax.inject.Inject instead of #Autowired. Similarly, you can use #Named instead of #Component. The documentation has more details.

Spring 3 bean is not being wired correctly

I have a web controller which I configure in the controller-config.xml using
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.ecommerce.web.controller" />
The controller has the #Controller annotation like below.
#Controller
public class HomeController
I have included the #Autowired annotation on the dependencies, but when I first start up the application I am unable to set any properties on the wired objects.
For example, I have a storeProfile object which when in debug mode I see has multiple properties set as it should.
But, when I try to set one of the storeProfile properties on an #Autowried bean it is still null or empty string!?
If you look at the attached images it shows that after I step past the line this.storeProfileContext.setStoreProfile(storeProf ile) the debugger still shows the storeProfile property as null
Actually, there are a couple dependencies which look like they are created (they are not null and the application functions), but I am unable to set anything on these objects.
I asked the same question on the Spring forums too - hoping to get this figured out.
Thanks so much!
That is because you are looking at the fields of the proxy, which gets created when you have <aop:scoped-proxy/>, if you invoke your getter for the set values, you should see the correct values retrieved from the proxied object.
The instances you are examining are CGLIB proxies.
CGLIB subclasses your beans, delegating all method invocations to the target beans.
So the fields of the super classes are still present but not used.

Generate Spring context files from template

I have a lot of repeating beans in my context definition files where only the names are different.
So when I want definition for the beans a, b and c I have to add:
<bean id="a" class="org.project.A" />
<bean id="b" class="org.project.B" />
<bean id="c" class="org.project.C" />
<bean id="aDao" class="org.project.ADAO" />
<bean id="bDao" class="org.project.BDAO" />
<bean id="cDao" class="org.project.CDAO" />
As there are many more than 3 beans, I want something like:
bean: a,b,c
templates:
- <bean id=":bean:" class="org.project.:bean:upper:" />
- <bean id=":bean:Dao" class="org.project.:bean:upper:DAO" />
Is there already a way to do this in Spring?
And if I have to implement my own solution, how can I make Spring call this function before trying to import the generated files?
There is no such functionality in Spring. You can write a maven plugin or some other pre-processing tool that searches for beans and generates the XML file.
Or you can let the Spring do this and drop the XML definitions altogether by annotating your beans with #Service, #Repository and friends.
If you use annotation based container configuration you don't need to generate the bean definition xml elements.
In one of my projects I used Apache Velocity to generate config for an IoC framework using a template file. The template language is simple yet powerful.
You may implement it as a Java app, call it from Ant, etc.
http://velocity.apache.org/
The last time I checked (several years ago), Spring used the following (simplified) algorithm to create beans:
Read XML files to get bean definition. The beans are not created immediately. Instead, their definitions are held in some data structures that later (in step 4) will be queried to create the beans.
Spring iterates over each bean definition, and uses reflection to check if a bean's class implements the BeanFactoryPostProcessor interface.
If so, that bean is created and its postProcessBeanFactory() operation is invoked. That method is typically coded to iterate over all the bean definitions and modify some of them, for example, to replace "${property.value}" with the value of a property read from a Java properties file.
Afterwards, the remaining ("normal") beans are created according to the (possibly modified) bean definitions.
It's been several years since I last looked at Spring, but if it still operates in the same way, then it might be possible to implement a class that implements the BeanFactoryPostProcessor interface and codes postProcessBeanFactory() to append a bean's id property onto its class property.

Categories

Resources