I've a weird problem of unable to instantiate a bean which is injected to another bean.
The PropertiesUtil is the bean in question. It's injected to the LoginController class as follows in my sn-servlet.xml
<bean name="/Login.html" class="org.sn.auth.LoginController">
<property name="dbUtil" ref="dbUtil"/>
<property name="propertiesUtil" ref="propertiesUtil"/>
</bean>
and my PropertiesUtil.java is
public class PropertiesUtil {
private Properties properties;
public PropertiesUtil() {
properties = new Properties();
try {
properties.load(ClassLoader.getSystemResourceAsStream(
"/resources/messages.properties"));
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
And the NullPointerException occurs at the line where I try to use the properties to load a resource. I'm really confused why it's null when I'm clearly instanting it in the previous line.
I've also tried injecting the properties instance as a constructor-arg and also as a property from the sn-servlet.xml, but all in vain.
Is there something like I'm not supposed to do any operations in a constructor when that bean is spring-injected to some other class?
Thanks for any ideas!
Check out the javadoc for ClassLoader.getResourceAsStream(). It returns null if the resource cannot be found. So it would seem that messages.properties cannot be found and the Properties.load() method will throw a NullPointerException when trying to read from a null InputStream.
Related
In my applicationContext.xml I have 2 beans with same class and different id(test and test1). The application context gets loaded correctly, but when I add #RequestMapping to one method then the bean creation fails with the below error. This used to work with AnnotationMethodHandlerAdapter but its failing with RequestMappingHandlerMapping and RequestMappingHandlerAdapter.
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'test1' bean method
public java.lang.String com.test.render()
to {[/render],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'test' bean method
Please suggest how to fix this.
Code:
applicationContext.xml
<bean id="test" class="com.abc.test" />
<bean id="test1" class="com.abc.test" />
Controller
#Controller
#RequestMapping( value ={"/test/", "/test1/"})
public class test {
#RequestMapping("render")
public String render ()
{
//some code here.
}
}
You can do it like this...
switch from singleton approach to prototype and inside the xml do
While programmatically define
class P1 {
#Autowire
NotSoSingleton prototypedBean;
}
class P2 {
#Autowire
NotSoSingleton prototypedBean;
}
class P3 {
#Autowire
NotSoSingleton prototypedBean;
}
Would this approach do?
I could find a work around with this. This solution if for the comments I posted on 21-May
I used order property to instantiate the custom defined RequestMappingHandlerMapping in the xml file and it worked!!
It took my custom defined RequestMappingHandlerMapping instead of the default one loaded by <annotation-driven>.
I am using Spring Dynamic Modules for the first time. I have tried to expose a service (simple listofValuesDAO Bean) through a bundle and am trying to inject it in another bundle to use the bean.
Below is configuration tag in osgi-context.xml of Bundle1 through which service was exposed:
<osgi:service ref="listOfValuesDAO" auto-export="interfaces"/>
and I am trying to fetch it in Bundle2 through below tag in osgi-context.xml:
<osgi:reference id="listOfValuesDAO" interface="com.dao.IListOfValuesDAO" />
The issue is that when I try to inject it in my bean in Bundle2 using below configuration:
<bean id="exportServiceImpl" class="com.service.impl.ExportServiceImpl">
<property name="listOfValuesDAO" ref="listOfValuesDAO"/>
</bean>
System throws below exception:
Exception in thread "SpringOsgiExtenderThread-85"org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exportServiceImpl' defined in URL [bundle://325.16:0/META-INF/spring/module-context.xml]:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'listOfValuesDAO' of bean class [com.service.impl.ExportServiceImpl]:
Bean property 'listOfValuesDAO' is not writable or has an invalid setter method. Did you mean 'listOfValuesDao'?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
Below is property in my ExportServiceImpl Class:
public class ExportServiceImpl implements IExportService {
IListOfValuesDAO listOfValuesDao;
public void setListOfValuesDao(IListOfValuesDAO listOfValuesDao) {
this.listOfValuesDao = listOfValuesDao;
}
public IListOfValuesDAO getListOfValuesDao() {
return listOfValuesDao;
}
}
Could someone please help me in resolving this issue?
It seems to be a problem with case inconsistency: listOfValuesDao and listOfValuesDAO are different names.
You use the first version in the Service, and the second in the XML bean definition. Try:
<bean id="exportServiceImpl" class="com.service.impl.ExportServiceImpl">
<property name="listOfValuesDao" ref="listOfValuesDao"/>
</bean>
I'm trying to inject a constructor that takes some arguments. After compiling Spring complains it couldn't find a default constructor (I haven't defined it) and throws BeanInstatiationException and NoSuchMethodException.
After defining a default constructor the exceptions don't appear anymore, however my object is never initialized with the argument constructor, only the default one is called. Does Spring really require a default constructor in this case? And if yes, how can I make it use the argument constructor instead of the default one?
This is how I wire everything:
public class Servlet {
#Autowired
private Module module;
(code that uses module...)
}
#Component
public class Module {
public Module(String arg) {}
...
}
Bean configuration:
<beans>
<bean id="module" class="com.client.Module">
<constructor-arg type="java.lang.String" index="0">
<value>Text</value>
</constructor-arg>
</bean>
...
</beans>
Stack trace:
WARNING: Could not get url for /javax/servlet/resources/j2ee_web_services_1_1.xsd
ERROR initWebApplicationContext, Context initialization failed
[tomcat:launch] org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'module' defined in URL [...]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class [com.client.Module]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: com.client.Module.<init>()
Spring only "requires" a default constructor if you plan on instantiating it without any arguments.
for example, if your class is like this;
public class MyClass {
private String something;
public MyClass(String something) {
this.something = something;
}
public void setSomething(String something) {
this.something = something;
}
}
and you set it up in Spring like this;
<bean id="myClass" class="foo.bar.MyClass">
<property name="something" value="hello"/>
</bean>
you're going to get an error. the reason is that Spring instantiates your class new MyClass() then tries to set call setSomething(..).
so instead, the Spring xml should look like this;
<bean id="myClass" class="foo.bar.MyClass">
<constructor-arg value="hello"/>
</bean>
so have a look at your com.client.Module and see how its configured in your Spring xml
Most probably you are using component-scanning and since you define annotation #Component for class Module it tries to instantiate the bean. You do not need #Component annotation if You are using XML for bean definition.
Just faced the same problem, i guess till now you might have solved the problem.
Below is what you could have changed your bean configuration to,
<bean id="module" class="com.client.Module">
<constructor-arg value="Text"/>
</bean>
I'm trying to configure JPA using just Java.
I got the idea that #EnableJpaRepositories would be the equivalent of jpa:repositories tag in xml, but I guess this is not the case?
I have this in my xml:
<jpa:repositories base-package="com.myapp.bla.bla" />
But if I remove it and instead use
#EnableJpaRepositories("com.myapp.bla.bla")
In my java config, I get an exception - I thought it was possible to configure JPA with Java since 1.2.0?
EDIT:
The root exception is:
No bean named 'entityManagerFactory' is defined
I assume the exception has to do with this definition in my config, but as said, everything works if I keep the xml and import it to my java config.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(new String[] { "com.myapp.bla.bla.model" });
factoryBean.setPersistenceProviderClass(HibernatePersistence.class);
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
factoryBean.setJpaProperties(props);
return factoryBean;
}
The problem is that your current configuration creates a bean called entityManagerFactoryBean. However, the error message of your root exception says that a bean named entityManagerFactory is not found.
You have two options for fixing this problem (pick the one you like the most):
Change the name of the method which configures the LocalContainerEntityManagerFactoryBean from entityManagerFactoryBean() to entityManagerFactory(). This creates a bean named entityManagerFactory.
Set the name attribute of the #Bean annotation to "entityManagerFactory". In other words, annotate the configuration method with #Bean(name="entityManagerFactory") annotation. This way you can specify the name of bean yourself and ensure that the name of the annotated method is ignored.
In my spring configuration file, I have declared one bean which is instantiated via a static factory method. The factory method invokes some remote services. The factory method returns null incase it is not able to access the remote service.
My problem everything goes wrong when the factory method returns null. and The spring initialization fails.
I really want to set the bean to null, if the factory method is not able to invoke the remote service.
Part of my config file is as follows :
<bean id="Helper" class="com.test.Helper">
<constructor-arg ref="myBean" />
</bean>
<bean id="myBean" class="com.test.Factory" factory-method="getBean" />
the getBean() method is as follows:
Factory {
public static Bean getBean() throws Exception{
try {
//Invokes some Remote Services and does some processing
....
....
//returns bean object
}catch(Exception e) {
return null;
}
}
}
Please help me how can I solve this.
Use MethodInvokingFactoryBean like so:
<bean id="myBean"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass"><value>com.test.Factory</value></property>
<property name="targetMethod"><value>getBean</value></property>
</bean>
you can return null . but be sure that b'coz of this null value there will be no NullPointerException raised . if it is raising just keep a simple if condition or return the control back from where it come or handle as think is perfect