Error in Spring bean injection : leads to a NullPointerException - java

I am totally new to Spring framework, bean injections etc, and working on a project organized in many sub-projects about it.
In the commons subproject, containing all Entities, DAOs, DS, I have a MyDS class implementing IMyDS and containing its EntityManager and DAO :
#PersistenceContext(unitName="myPersistenceUnit")
private EntityManager entityManager;
#Autowired
#Qualifier("myDAO")
private IMyDAO mainDao;
Then, I am trying to call this class from the Web part of my project, like this:
#Autowired
private IMyDS myDS;
// then I try to call a function of IMyDS, and get an error at this line :
protected ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ReefPresentationException {
myDS.callFunction(form);
}
But it doesn't work, giving me a NullPointerException. So far I've guessed the bean is not correctly injected, so I tried to add some information in my application-context-spring.xml file :
<bean id="myDS" class="com.my.project.service.IMyDS" />
And I get this error :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.my.project.service.IMyDS]: Specified class is an interface
So I tried instead to declare the class :
<bean id="myDS" class="com.my.project.service.internal.MyDS" />
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDS' defined in ServletContext resource [/WEB-INF/config/application-context-spring.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
So I really have no idea of what is wrong right now...
Thanks for your help

The errors says it all. You have defined your interface IMyDS as a bean and Spring can't instantiate the interface.

Related

Multiple entityMangagerFactories ( 1PC pattern used) leads to java.lang.IllegalStateException: 'url' not set exception

I have the Spring Maven project using Java 11. Jboss WIldfly 15.0.1 Final is my deployment server.
To import data (objects using Hibernate) from one data source to another data source (MySQL)- I have added one primary entityManagerFactory with JpaTransactionManager and I have 2 other entity manager factories separate perisistenceUnits and a chainedTransactionManager being used(for 1 Phase commit-1PC commnit).
When deploying the war, sometimes, I get the below exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'someDAO': Injection of persistence dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'onetimeConfig': Injection of persistence dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityMgrFactory2' defined in class path resource [com/path/ImportConfig.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[javax.persistence.EntityManagerFactory]: Factory method 'entityMgrFactory2' threw exception;
nested exception is java.lang.IllegalStateException: 'url' not set
someDAO class header is:
#Transactional(rollbackFor = {Exception.class})
#Repository("someDAO")
public class SomeDAOImpl extends ParentDAOImpl implements SomeDAO {
The someDAO class extends the ParentDAOImpl class in which the primary entityManagerFactory is used and is also mentioned using #DependsOn. So, why does on deploy the creation of someDAO is trying to trigger the creation of entityMgrFactory2 when entityManagerFactory is mentioned in?!
#Repository("parentDAOImpl")
#DependsOn({"entityManagerFactory"})
public class ParentDAOImpl implements ParentDAO, Serializable {
#PersistenceContext
private transient EntityManager entityManager;
...
The problem never replicates on my local machine. It does occurs only while deploying on other servers and deployment fails due to this. And also the exception sometimes mentions someDAO and other times a different DAOclass that extends ParentDAOImpl.
Please help me, I am a novice.

Implementing annotation based Spring AspectJ (JavaConfig)

We're trying to implement AspectJ #Aspect into our existing software for executing some code after a service call is made.
Note:
We have service interfaces and implementations being #Autowired
throughout the project via rest controllers as well as other service implementations.
This project is entirely a Java Configuration with no XML whatsoever.
We're using Spring 4.1.2 RELEASE deployed on Tomcat 7.0.54.
Issue:
When we added #EnableAspectJAutoProxy into our main #JavaConfig, we experience the following exception:
Unresolvable circular reference.
Which fails every #Autowired attempt on a long list of beans.
Tried:
Removed the #EnableAspectJAutoProxy annotation which autowires everything correctly but our #Aspect never gets invoked.
Added the CGLIB support in the annotation by declaring
proxytargetclass=true to no avail.
We've tried following this documentation directly from Spring: #EnableAspectJAutoProxy Javadoc
This seems to be an issue with AspectJ's proxy mechanism dealing with autowired dependencies.
Why does this occur when we add the #EnableAspectJAutoProxy?
Our Java Config:
#Configuration
#EnableWebMvc
#EnableJpaRepositories(basePackages ={"com.company.product.persistence.repository"})
#EnableTransactionManagement
#EnableSwagger
#EnableAspectJAutoProxy
#PropertySource({"classpath:hibernate.properties",
"classpath:auth.properties",
"classpath:mail.properties",
"classpath:locations.properties"
})
#ComponentScan(basePackages = {"com.company.product"})
public class WebConfig extends WebMvcConfigurerAdapter {
//Bean declarations here.
//Note: All services/repos/controllers are annotation based.
}
Aspect implementation:
#Aspect
#Component
public class PostMessageAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#After("execution(*com.company.product.persistence.serviceImpl.event.eventServiceImpl.methodCall(..))")
public void postMessageRun(final JoinPoint joinPoint) {
logger.info("CALLED AFTER METHOD");
}
}
Update:
Managed to get AOP/AspectJ working perfectly fine on one dev machine only requiring a minor change to our Spring Security config. We are both using Intellij, openJDK 1.7.0_65 on Ubuntu 14.0.4 running on default instances of Tomcat 7.0.56. On the other machine running the same software stack, gets the following.
Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingMessageController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.event.DispatchingEventService com.apx.efm.controllers.message.DispatchingMessageController.dispatchingEventService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dispatchingEventServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAd dressesService com.apx.efm.persistence.serviceImpl.event.DispatchingEventServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingAddressServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingService com.apx.efm.persistence.serviceImpl.building.BuildingAddressServiceImpl.buildingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'buildingServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.apx.efm.persistence.service.building.BuildingAddressesService com.apx.efm.persistence.serviceImpl.building.BuildingServiceImpl.buildingAddressesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.aopalliance.intercept.MethodInterceptor]: Factory method 'methodSecurityInterceptor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.apx.efm.persistence.service.user.EfmUserService com.apx.efm.application.config.SecurityConfig.efmUserService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'efmUserServiceImpl' defined in file [/home/apxdev4/Development/GitRepositories/efim-restful-web-service/target/EFIM/WEB-INF/classes/com/apx/efm/persistence/serviceImpl/user/EfmUserServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'methodSecurityInterceptor': Requested bean is currently in creation: Is there an unresolvable circular reference?
This was entirely an issue with our Spring configuration. Our Spring Security configuration was trying to #Autowired beans while they were still in the middle of being processed by our main application configuration. We solved this by ensuring that Spring Security gets configured after the main #Configuration.
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
// Initialize web mvc
appContext.setDisplayName("APP");
appContext.register(WebConfig.class);
appContext.register(SecurityConfig.class);
// Rest omitted (listeners, dispatcher servlet, etc.)
}

Any way to override bean definition for spring data jpa repository?

We have a sample app that showcases some things we are doing client side. It pulls in a few internal libraries to get everything functional. It dummies in some hard-coded data so it doesn't have to be concerned with any kind of persistence mechanism.
In some of these libraries that are pulled in, there are spring data jpa repositories. Something like this:
public interface MyLibraryEntityRepository extends JpaRepository<MyLibraryEntity, Long>
{
//...
}
When the server starts up, I get an error like this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myLibraryEntityRepository': Cannot create inner bean '(inner bean)#788f64f1' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#788f64f1': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
It can't find the entityManager, but I don't want to have to use an entityManager. So, in an attempt to override the myLibraryEntityRepository bean, I added the following to my Java config:
#Bean
public MyLibraryEntityRepository getMyLibraryEntityRepository()
{
return myDummyImpl();
}
However, this results in the same error.
Is there any way I can override the bean definition for the spring data jpa repository so that I can use my own dummy implementation and not have to configure an entityManager in my app?
You can use #Bean(name="dummyBean") and the in the #Autowired use the annotation #Qualifier("dummyBean")

Bean creation exception

My application context looks likt this,
<bean id="caseTxBo" class="gov.case.rcp.bo.impl.caseTxBoImpl" >
<property name="caseTxDao" ref="caseTxDao" />
</bean>
<bean id="caseTxDao" class="gov.case.rcp.dao.impl.caseTxDaoImpl" >
<property name="sessionFactory" ref="sessionFactory" />
Action class gets the context like this:
ServletContext context = request.getSession().getServletContext();
BeanFactory factory = WebApplicationContextUtils.
getRequiredWebApplicationContext(context);
CaseTxBOImpl caseTxBo = (
caseTxBoImpl) factory.getBean("caseTxBo");
List<caseTxPmt> errorVarList =
caseTxBo.getcaseTxDao().findAllcaseTx();
model.put("caseTxList", caseTxList);
BOImpl implements Dao and DAOImpl implements Dao:
DaoImpl has the implementation and returns caseTxList.
but I get a runTimeException as
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caseTxBo' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Cannot resolve reference to bean 'caseTxDao' while setting bean property 'caseTxDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caseTxDao' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [gov.case.rcp.pp.dao.impl.CaseTxDaoImpl]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
follows:
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
Where did i go wrong?
Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
follows:
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
The error message is pretty clear. Open your CaseTxDaoImpl and make sure there is a following method there:
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
BTW this:
ServletContext context = request.getSession().getServletContext();
BeanFactory factory = WebApplicationContextUtils.
getRequiredWebApplicationContext(context);
factory.getBean("caseTxBo")
is pretty low-level usage of Spring and an anti-pattern. Are you using any web framework? Typically they integrate with Spring quite well.

Spring bean creation error

So I've been following the Spring documentation, specifically this part,
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators on Dependency Injection, but whenever my code runs, I get an error about bean creation.
Here is portion of my code that I tried to base off the ExampleBean example,
public class TimeFeedHandler implements MessageListener {
String msgID = null;
TimeBayeuxService timeBayeuxService;
public void setTimeBayeuxService(TimeBayeuxService timeBayeuxService) {
this.timeBayeuxService = timeBayeuxService;
}
And my Spring XML file looks like this,
<!-- A POJO that implements the JMS message listener -->
<bean id="timeFeedHandler" class="com.example.streaming.time.TimeFeedHandler" >
<property name="timeBayeuxService" ref="timeBayeuxService"> </property>
</bean>
The error I get is,
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL....
Any ideas why or what I'm doing wrong?
Edit, here is the TimeBayeuxService bean,
<!-- Time BayeuxServices -->
<bean id="timeBayeuxService" class="com.example.streaming.time.TimeBayeuxService" lazy-init="true">
<constructor-arg><ref bean="common.bayeux" /></constructor-arg>
<property name="timeBean" ref="time.time" />
</bean>
Here is more of the error. The full error log from STS is wayyyyy too long. I feel like I'm not referencing the TimeBayeuxService bean properly but logically I can't seem to see what I'm doing wrong.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeFeedHandler' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Cannot resolve reference to bean 'timeBayeuxService' while setting bean property 'timeFeedHandler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeBayeuxService' defined in URL [file:/Users/nullpoint/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.example.streaming.time.TimeBayeuxService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
Here is a portion of the TimeBayeuxService class
public class TimeBayeuxService {
private Bayeux bayeux;
private static StreamingTimeLogGatherer logGatherer;
String testMsgTS = "This is a test message from the original service";
public TimeBayeuxService(Bayeux bayeux) extends SomeBayeuxService{
super(bayeux, TimeBayeuxService.class.getName());
this.bayeux = bayeux;
final Bayeux fbayeux = bayeux;
this.logGatherer = logGatherer;
LogServlet.addLogGatherer(logGatherer);
startThread(fbayeux, testMsgTS, true);
}
timeFeedHandler has a dependency on timeBayeuxService. It can't initialize timeBayeuxService due to NullPointerException so spring can't inject the bean.
According to the error message the NullPointerException happened in the constructor of com.example.streaming.time.TimeBayeuxService. How are you creating common.bayeux bean? Please paste the constructor code for TimeBayeuxService class. Is it an interface? Then you should put the implementation class in the bean definition.
The possible places for NPE. Without the complete stack trace I have to guess the following lines of code:
It can happen inside the constructor of the super class.
These 2 methods: LogServlet.addLogGatherer(logGatherer); startThread(fbayeux, testMsgTS, true);

Categories