I have a web application that executes on tomcat 6.
I have a MysqlDb class that uses a BasicDataSource from a spring JDBC.
so far I've used the following bean configuration in web.xml:
<bean id="MysqlDb" class="com.xpogames.gamesisland.mysql.MysqlDb">
<property name="idDataSource" ref="idDataSource"/>
</bean>
and I had the following setter function:
public void setidDataSource(BasicDataSource ds) {
this._dataSource=(DataSource)ds;
this._simpleJdbcTemplate = new SimpleJdbcTemplate(_dataSource);
this._jdbcTemplate = new JdbcTemplate(_dataSource);
}
I want to convert my class to use static functions, so I created an empty private constructor so the class won't explicitly instantiated by callers.
besides that I changed the setidDataSource function to a static function, but when I try to do that I get the following error:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'idDataSource' of bean class [com.xpogames.gamesisland.mysql.MysqlDb]: Bean property 'idDataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
is there a way to resolve this issue in web.xml or do I need to manually
fetch the ServletContext
ServletContext servletContext = this.getServletContext();
this._context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
and fetch the bean from there and just remove the lines i printed here from web.xml ?
For one, you've declared the setter setidDataSource. It should be setIdDataSource. The first letter of a property must be a capital letter after the word set.
Also, a setter method must not be static but an instance method.
Spring-beans are by default singletons, you do not need to implement your class as a singleton as long as you use the bean from the context.
The simplest answer to your question is getting the bean from the context after setting the datasource in the context, but I thought you want to stay away from the context.
Static setters for class are of course possible (they would just set static property for all instances), but in IoC pattern (which is used in spring), bean is instance, and term "property of bean" always means "property of instance of class" - consider it as limitation of given IoC implementation.
I understand know that I had a bad implementation idea. I still need a constructor, so building a class with static functions and static init is a bad idea, and trying to execute a static setter from a bean is not logical and impossible.
Instead I changed the class to be a singleton class, so I will be able to use it anywhere in my application and it will be constructed only once.
thanks for all the information.
update
I still don't know if that's a good method, but at least it works.
in my red-web.xml (consider it as spring applicationContext.xml), I have the following:
<bean id="MysqlDb" class="com.xpogames.gamesisland.mysql.MysqlDb" init-method="getInstance">
<property name="idDataSource" ref="idDataSource"/>
</bean>
Here it creates a MysqlDb bean and configure it to use the getInstance() init method if MysqlDb Class. i made sure to have a setidDataSource() function in mysqlDb class for the datasource to be properly set.
<bean id="web.handler" class="com.xpogames.gamesisland.Application">
<property name="MysqlDb" ref="MysqlDb"/>
</bean>
Here, I create the main bean of my application and I made sure to have the function setMysqlDb for the MysqlDb class to be set from the bean configuration.
So far mysqlDb acts as a singelton class because it's constructor is protected and it creates the instance only once:
public static MysqlDb getInstance() {
if (instance == null) {
instance = new MysqlDb();
}
return instance;
}
The problem that I encountered was that in other parts of my application whenever I used getInstance(), the MysqlDb class would come up and all the variables that where set with setidDataSource where null.
so resolve that issue I created another function called setInstance in mysqlDb:
public static void setInstance(MysqlDb db) {
instance=db;
}
this is my main setMysqlDb function in my main application:
public void setMysqlDb(MysqlDb db) {
this._mysqlDb=db;
/* it seems that without forcing a setInstance on the class, whenever other classes
* would try to getInstance(), variables that are supposed to be configured by the bean
* would be empty. this resolves that issue
*/
MysqlDb.setInstance(db);
}
so this configuration works. it's obviously not the recommended or best solution! but it seems that I need to read and learn further before I come up with a better solution.
Related
Is it possible to chain methods in factory-method in spring to create beans. For example, I have the following API:
SomeObject.builder().build();
Is there some way I can create this bean in spring XML config directly without creating 2 beans? For example,
<bean id="fooBar" class="com.foo.bar.SomeObject" factory-method="builder().build"/>
Note: The SomeObject.builder() call returns a SomeObjectBuilder object(private static class within SomeObject).
You can't do that. You just specify a single method (even without the brackets). But in SomeObject class you can create a static method that does that for you. For example:
static SomeObject newFactoryMethod(){
return builder().build();
}
And add it to the XML:
<bean id="fooBar" class="com.foo.bar.SomeObject" factory-method="newFactoryMethod"/>
Why my code is failing with the below error when I AUTOWIRE the no arg constructor but it runs fine when I autowire only the single arg constructor
Exception in thread "main" java.lang.NullPointerException
Here is TennisCoach Class code snippet
#Component // this is bean id
public class TennisCoach implements Coach {
public TennisCoach(FortuneService thefortuneservice) {
System.out.println(" inside 1 arg constructter");
fortuneservice = thefortuneservice;
}
#Autowired
public TennisCoach() {
System.out.println(" inside 0 arg constructter");
}
}
Coach theCoach = myapp.getBean("tennisCoach", Coach.class);
System.out.println(theCoach.getDailyFortunes());
How are things working behind the scene?
If you have only one constructor in a class, you don't need to use #Autowired--Spring understands that there's only one option, so it uses that one. But you have two constructors, so you need to tell Spring which one to use.
When you invoke the default constructor, however, what do you expect to happen? You don't set up your variables anywhere at all, but you are trying to read from them.
Constructor with no arguments doesn't want you put #Autowired on it as you are not injecting anything in its arguments (since there are none). #Autowired is required for constructor with arguments however.
#Component annotation above the class will create your bean via calling the default constructor and you can use that anywhere but need to make sure that you don't call anything on the fortuneservice as that will result in a null ptr exception unless you initialize it. On the contrary, if you put #Autowired annotation on top of constructor with argument and it runs fine then that means that the fortuneservice bean that you have declared elsewhere will now be injected inside this class and no null ptr exception if you call some method on that.
Adding to the previous to answers - think about the term "constructor injection". You are INJECTING references via constructor parameters. When you #Autowire an empty constructor, there isn't anything to inject. Therefore you get a NullPointerException when attempting to access the field that was supposed to have a reference injected into.
I would like to use #Value on a property but I always get 0(on int).
But on a constructor parameter it works.
Example:
#Component
public class FtpServer {
#Value("${ftp.port}")
private int port;
public FtpServer(#Value("${ftp.port}") int port) {
System.out.println(port); // 21, loaded from the application.properties.
System.out.println(this.port); // 0???
}
}
The object is spring managed, else the constructor parameter wouldn't work.
Does anyone know what causes this weird behaviour?
Field injection is done after objects are constructed since obviously the container cannot set a property of something which doesn't exist. The field will be always unset in the constructor.
If you want to print the injected value (or do some real initialization :)), you can use a method annotated with #PostConstruct, which will be executed after the injection process.
#Component
public class FtpServer {
#Value("${ftp.port}")
private int port;
#PostConstruct
public void init() {
System.out.println(this.port);
}
}
I think the problem is caused because Spring's order of execution:
Firstly, Spring calls the constructor to create an instance, something like:
FtpServer ftpServer=new FtpServer(<value>);
after that, by reflection, the attribute is filled:
code equivalent to ftpServer.setPort(<value>)
So during the constructor execution the attribute is still 0 because that's the default value of an int.
This is a member injection:
#Value("${ftp.port}")
private int port;
Which spring does after instantiating the bean from its constructor. So at the time spring is instantiating the bean from the class, spring has not injected the value, thats why you are getting the default int value 0.
Make sure to call the variable after the constructor have been called by spring, in case you want to stick with member injection.
I followed the following example of dependency injection: http://www.tutorialspoint.com/spring/spring_autowired_annotation.htm
For example the TextEditor class (from the above link):
public class TextEditor {
private SpellChecker spellChecker;
#Autowired
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker( ) {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
How can these dependencies/classes be instantiated, while they don't have any constructor?
Is Java simply making an object of that type, that is empty? Like an empty parameter constructor without any code?
Thanks for making this more clear!
Unless specified otherwise, every Java class has the default constructor. So here, you have a default public TextEditor() constructor, even though you haven't coded for it. (You could code it if you needed to change its visibility from public, declare a thrown exception, etc.)
So yes, Spring calls this default constructor - then calls the setSpellChecker method (as annotated, and through reflection) to populate it.
If no constructor is defined, a class can be instantiated via the no-argument default constructor.
So, the framework calls that constructor (supposedly using reflection) and then uses the set method to set the one field of the freshly created class.
The example above is using Spring annotations and Spring context file and those are the main and most important parts of the project, considering the DI.
So in the context file you have following line:
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
this defines a class with reference spellChecker that mapps to a class com.tutorialspoint.SpellChecker and once the compiler find such property in a method that is marked as #Autowired on instantiation of the object it injects/sets the relevant version of the required dependency.
In cases where a property doesn't match a reference tag in the applicationContext.xml file Spring is trying to map the type e.g. property with name mySpecialSpellChecker which has type of com.tutorialspoint.SpellChecker still will be mapped to bean with id="spellChecker" if there are more than one of same type Spring won't instantiate your object and you might get compile time error as Spring can't know which version of the two (or more) is the correct one so this requires developer input.
This is the order of execution:
instantiate textEditor, this has default constructor that is not visible in the code public TextEditor ()
the new instance is set in a pool of available objects with reference textEditor
instantiate spellChecker and add to the pool of available object with relevant reference/label
all #Autowired properties/methods are set/called with relevant objects in this case Spring calls: setSpellChecker(spellChecker)
I have 4 singleton classes with private constructors
and I'm trying to create bean property for all the 4 classes.
The main problem is, I'm able to create the bean for 3 classes
and these 3 classes have similar structure with a getInstance method and
a private constructor() (Singleton class) but the fourth and the last one
is throwing an exception (Exception message is pasted below)
Please find below the getInstance method, the private constructor
and the bean id declaration. Which is same across all the four bean declarations
But If I change the constructor from "Private" to "Public" then
I dont get the error. Could anyone throw any light on what is happening? Since the other three classes have private constructors and they work perfectly fine
The getInstance() method
public static ApplicationConfiguration getInstance() throws IOException,
IllegalArgumentException, InconsistentDataException {
ApplicationConfiguration result = instance.get();
if (result == null) {
try {
// Check again if already created
result = instance.get();
if (result == null) {
result = new ApplicationConfiguration();
}
} finally {
// something here
}
}
return result;
}
The private constructor
private ApplicationConfiguration() throws Exception {
// call a method here
}
The bean property declaration
<bean id="configManager" class="com.manager.ApplicationConfiguration" factory-method="getInstance" />
<bean id="configEnricher" class="com.enricher.ApplicationConfiguration" factory-method="getInstance" />
<bean id="configBussiness" class="com.validationservice.ApplicationConfiguration" factory-method="getInstance" />
The above three works
This bean property is throwing the error
<bean id="configEviction" class="com.evictionservice.ApplicationConfiguration" factory-method="getInstance" />
The Exception message
[#|2012-08-07 11:53:21,130|ERROR|RMI TCP Connection(226)-172.18.36.14|org.springframework.
web.context.ContextLoader||slodev-rhngp5.mblox.com|core-1|Context initialization failed|#]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'co
nfigEviction' defined in ServletContext resource [/WEB-INF/camel-context.xml]: Initializat
ion of bean failed; nested exception is org.springframework.aop.framework.AopConfigExcepti
on: Could not generate CGLIB subclass of class [class com.evictionservice.ApplicationConfiguration]:
Common causes of this problem include using
a final class or a non-visible class; nested exception is java.lang.IllegalArgumentExcepti
on: No visible constructors in class com.evictionservice.ApplicationConfiguration
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.do
CreateBean(AbstractAutowireCapableBeanFactory.java:526)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.cr
eateBean(AbstractAutowireCapableBeanFactory.java:455)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(Abstr
actBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingl
eton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(Abstrac
tBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractB
eanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstant
iateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactor
yInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(Abstract
ApplicationContext.java:425)
:
The problem is not the bean creation itself (as you already noticed, that's not different from the other beans). The issue seems to be related to some AOP configuration that you're trying to use. If you want to create a proxy for that class, it cannot do it with CGLIB because the class cannot be subclassed (since it has a private constructor).
The only way to get around this (given your current design) is to create an interface that will be implemented by the ApplicationConfiguration class and then create the proxy for that interface instead of proxy-ing the class.