Java Beans instantiating wrong bean - java

In my Spring-Module.xml I have two beans:
<bean id="two_num" class="main.java.com.shen.Generator">
<property name="length" value="8" />
<property name="categories" value="3" />
...
</bean>
<bean id="six_num" class="main.java.com.shen.Generator">
<property name="length" value="6" />
<property name="categories" value="1" />
<property name="numeric" value="numeric" />
...
</bean>
And I instantiate my class like so:
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
Generator obj = (Generator) context.getBean("two_num");
For some reasons, java is always instantiating my second bean despite me explicitly saying that I want the bean "two_num". If I were to flip the order around, and have "six_num"'s bean above "two_num", it would get the bottom bean. :| What's going on? I'm so confused. Is my method for selecting a specific bean wrong?
EDIT: after adding one more bean to it this is what I get when I run my program:
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#e949f69: defining beans [two_num,six_num,four_num]; root of factory hierarchy
And as expected, when I call a print method in my class, I can see that the current object is instantiated with the information dicated in four_num, and not "two_num"

Certainly remove static modifiers on your fields, as already suggested.
Also, if you want 'singletons' modify your XML:
<bean id="two_num" class="main.java.com.shen.Generator" scope="singleton">
<property name="length" value="8" />
<property name="categories" value="3" />
...
</bean>
So you'll only get a single instance of each bean. You'll still get multiple instances of Generator, but only one per bean.

Based on comments, I can only assume that the Generator class looks something like this
public class Generator {
private static length;
private static categories;
//getters/setters
}
Given that i dont have a full class to work with, i can only recommend removing the static modifier as it would contradict the way you want to use the class.

Related

Save Spring XML Configuration

Forgive me if this has been answered before ...
I want to load a spring configuration xml file from disk, have the user modify settings, then save the modifications back to the xml file, for initialization during a subsequent run of the application.
For instance, say a class has a collection of classes, each with their own bean configurations. Through the UI, the user may reconfigure any of the sub-classes and/or add/remove any sub-classes from the collection.
Example application-context.xml:
<beans>
<bean id="mainClass" class="...">
<property name="subClassList">
<list>
<ref bean="subClassA" />
<ref bean="subClassB" />
</list>
</property>
</bean>
<bean id="subClassA" class="...">
<property name="var1" value="1" />
</bean>
<bean id="subClassB" class="...">
<property name="var2" value="100" />
</bean>
</beans>
So, not only do I want to allow the user to modify var1 & var2 in the application and save the configuration, but the user could remove subClassB from the list or add subClassC to the list, within the application, then save the configuration.
Also, the application is a desktop app, not web-based. In addition, "mainClass" is not the class that contains the application entry point, "main()". Think of "mainClass" as a container, with a collection of other classes, each of which has a "process()". So, the parent class, mainClass, iterates through each subClass, runs process(), then evaluates what the overall result will be. Adding subclasses and modifying subClass parameters, then saving the configuration is the goal.
Thanks in advance,
Eric

How do you know the actually value for a property set by a map of beans on java?

Ive found this configuration on a applicationContext xml and I still dont understand it (even if I found info about it, is not clear) could someone give me an idea of how java chooses the right bean for its property? I did not find this bean in other file of the project context, seems like is "magic"
<bean id="mailCreator" class="com.project.ConfigurableXferEmailCreator">
<property name="mailCreatorMap">
<util:map id="mailCreatorMap" key-type="java.lang.String"
value-type="com.project.BaseMailCreator">
<entry>
<key>
<util:constant static-field="com.project.creatorType.TYPE1"/>
</key>
<bean class="com.project.creator1" parent="baseCreator">
<property name="service" ref="someService1" />
</bean>
</entry>
<entry>
<key>
<util:constant static-field="com.project.creatorType.TYPE2"/>
</key>
<bean class="com.project.creator1" parent="baseCreator">
<property name="service" ref="someService2" />
</bean>
</entry>
.... and so on
I really have no idea how java recognizes which one will use, I just know it uses the right service but I dont see where is being specifically set, could someone give me a hand?
I checked couple of sites like this but still no idea , does it call all services??
http://www.java2s.com/Tutorials/Java/Spring/0140__Spring_Map_Properties.htm
Your question:
"how java chooses the right bean for its property"
I assume you mean for example this line:
<property name="service" ref="someService1" />
if you do not see another XML bean element that defines "someService1"
fr example:
<bean id="someService1" class="com.project.SomeService1Impl">
Then it exists in the Java Code
try to find an annotation like below
#Service("someService1")
public class SomeService1Impl {
...
How?:
Spring loads "someService1" in the Spring Context on initialization , so the XML can reference it.

Spring bean property define

I have two class A and B . A is parent and B is child class.
am calling the class B methods.but class b accessing the methods of A.and i want to set a property in class A. So defined the property like
<bean name="b" class="com.dao.B" parent="parent">
<property name="utility" ref="utility"/>
</bean>
<bean class="com.dao.A" id="parent">
<property name="utility" ref="utility"/>
</bean>
and in the class A have a property named utility and with a setter...
when i try to get the instance i got null...
can u help me to set that
As A has a public setter of field utility then you can directly set property of object in class A from B like.
<bean name="b" class="com.dao.B">
<property name="utility" ref="utility"/>
</bean>
here utility is in class A with public setter and we are set value in B bean.
Do not use parent attribute, try this
<bean id="b" class="com.dao.B" >
<property name="utility" ref="utility"/>
</bean>
<bean id="a" class="com.dao.A">
<property name="utility" ref="utility"/>
</bean>
Is A a parent (in spring means) of B?
If not, just remove parent="parent" and id="parent" and you will be fine.
Read spring docs about abstract beans definition and use of parent.

Autowired dependencies coming back null (Every single one of them)

Spring seems to resolve and create the autowired objects just fine on boot up. But when I try to access them they come back as null. Anyone have any guesses on what might be going on?
Also XML info is blank as I'm only allowed one hyperlink...
<beans xmlns=""
xmlns:xsi=""
xmlns:p=""
xmlns:mvc=""
xmlns:context=""
xsi:schemaLocation="...only allowed one hyperlink" default-autowire="byName">
<mvc:annotation-driven />
<context:component-scan base-package="com.blah.controller"/>
<context:component-scan base-package="com.blah.*.service"/>
<context:component-scan base-package="com.blah.*.dao"/>
<context:annotation-config />
public class AuthFilter extends UsernamePasswordAuthenticationFilter {
#Autowired
private ProfileService profileService;
//.... Do more stuff below that shows profileService coming back as null.
}
I was able to use a debugger to show that the object was being initialized. I can paste my logs here if you guys want but that's a lot to back edit :).
Adding a bit to this where authfilter is defined:
<b:bean id="authenticationFilter" class="com.blah.auth.AuthFilter">
<b:property name="authenticationManager" ref="authenticationManager" />
<b:property name="filterProcessesUrl" value="/login/validate" />
<b:property name="usernameParameter" value="username" />
<b:property name="passwordParameter" value="password" />
<b:property name="authenticationSuccessHandler" ref="authSuccessHandler" />
<b:property name="authenticationFailureHandler" ref="authFailureHandler" />
</b:bean>
The component scan is in springapp-servlet.xml
I've created a pastebin of the boot logs. No dice with moving the component scan. http://pastebin.com/ttC5MPnQ
see if the there is something suspicious in the logs
it appears to me that AuthFilter is not a spring bean - either map it in the xml config, or annotate it with #Component.
remove default-autowire="byName" if you don't have a compelling reason to have it set so.
make sure you use that filter from within the context, and not instantiating it yourself.
make sure you are not referring to a bean defined in a parent context (for example - a bean defined in applicationContext.xml can't access a bean defined in dispatcher-servlet.xml)
place a component-scan in the applicationContext.xml (not the servlet one). (You can retain the one in the servlet xml but limit it to web packages only)

How do I create a spring bean for a Java double primitive?

I'd like to create a spring bean that holds the value of a double. Something like:
<bean id="doubleValue" value="3.7"/>
Declare it like this:
<bean id="doubleValue" class="java.lang.Double">
<constructor-arg index="0" value="3.7"/>
</bean>
And use like this:
<bean id="someOtherBean" ...>
<property name="value" ref="doubleValue"/>
</bean>
It's also worth noting that depending on your need defining your own bean may not be the best bet for you.
<util:constant static-field="org.example.Constants.FOO"/>
is a good way to access a constant value stored in a class and default binders also work very well for conversions e.g.
<bean class="Foo" p:doubleValue="123.00"/>
I've found myself replacing many of my beans in this manner, coupled with a properties file defining my values (for reuse purposes). What used to look like this
<bean id="d1" class="java.lang.Double">
<constructor-arg value="3.7"/>
</bean>
<bean id="foo" class="Foo">
<property name="doubleVal" ref="d1"/>
</bean>
gets refactored into this:
<bean
id="propertyFile"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:my.properties"
/>
<bean id="foo" class="Foo" p:doubleVal="${d1}"/>
Why don't you just use a Double? any reason?
Spring 2.5+
You can define bean like this in Java config:
#Configuration
public class BeanConfig {
#Bean
public Double doubleBean(){
return new Double(3.7);
}
}
You can use this bean like this in your program:
#Autowired
Double doubleBean;
public void printDouble(){
System.out.println(doubleBean); //sample usage
}

Categories

Resources