NullPointerException while using #Autowired in maven webapp - spring

I am trying to integrate Jersey with Spring using maven webapp-archetype. When I get the object form the ApplicationContext I see my code executing, but when I try to use #Autowired it throws me NullPointerException. Following are the code snippets:
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pack.resource" />
<bean id="person" class="com.pack.resource.Person">
<property name="name" value="SomeNamexxxx" />
</bean>
Person.java
package com.pack.resource;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
}
Hello.java
package com.pack.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Component;
#Component
#Path("/hello")
public class Hello {
#Autowired
Person person;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getName() {
return person.getName();
}
}
But when I use ApplicationContext.getBean("person").getName() it gives me the actual value inside the bean property.
Why is #Autowired annotation not working as it should. Kindly help me.
TIA!

Related

spring aop logging advice is not getting called

I am writing simple aspect with simple logging advice which will be called upon setter of class.
Below is code Snippet
AopMain.java
package com.example.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.test.model.Triangle;
import com.example.test.service.ShapeService;
public class AopMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//ShapeService shapeService = context.getBean("shapeService", ShapeService.class);
//shapeService.getTriangle().setName("triangle");
Triangle triangle = new Triangle();
triangle.setName("triangle class");
System.out.println(triangle.getName());
}
}
Triangle.java
package com.example.test.model;
public class Triangle {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println(name);
}
}
LoggingAspect.java
package com.example.test.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.example.test.model.Triangle;
#Component
#Aspect
public class LoggingAspect {
#Before("execution(public * *(..))")
public void LoggingAdvice(JoinPoint jPoint) {
System.out.println("Advice run. Get method is called " + jPoint.getTarget());
Triangle triangle = (Triangle) jPoint.getTarget();
}
#Before("args(name)")
public void test(String name) {
System.out.println("logging advice args " + name);
}
}
Output
triangle class
triangle class
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- <bean id="triangle" class="com.example.test.model.Triangle">
<property name="name" value="Triangle Name"></property>
</bean> -->
<bean id="circle" class="com.example.test.model.Circle">
<property name="name" value="Circle Name"></property>
</bean>
<bean id="shapeService"
class="com.example.test.service.ShapeService" autowire="byType" />
<aop:aspectj-autoproxy />
<context:component-scan
base-package="com.example.test" />
</beans>
spring is working properly.
I do not understand why aspect is not gettting called.
please help me to understand this issue.

How to solve error message when try to start jpa on spring-boot?

I have spring+jpa+rest application on spring-boot(try to implement)
Application for spring-boot:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.persistence.PersistenceContext;
#SpringBootApplication
#ComponentScan("package")
#EnableJpaRepositories(basePackages = "package.dao", entityManagerFactoryRef = "emf")
#ImportResource("applicationContext.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I have rest - controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import package.myService;
#RestController
public class TestController {
#Autowired
private MyService myService;
#PostMapping("create")
public void test1(){
}
#PostMapping("{id}")
public void test2(#RequestBody Object object){
}
#GetMapping("{id}")
public void test3(#PathVariable Long id){
}
}
Entity:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.math.BigDecimal;
#Entity
public class MyEntity {
#Id
#GeneratedValue
private Long id;
private String name;
public MyEntity() {
}
public MyEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Repository is:
MyEntityRepository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface MyEntityRepositoryextends JpaRepository<myEntity, Long>{
public void findNameById(#Param("id") Long id);
}
application context in resouces:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<bean id="riskMetricService" class="ru.sbrf.risks.services.data.service.RiskMetricServiceImpl"/>
</beans>
If needs, I can add pom.xml
I have error message when try to strat: APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in
org.springframework.data.rest.webmvc.RepositorySearchController
required a bean named 'emf' that could not be found.
Action:
Where need to locate file with dbconnection configs?
How to solve this error message?
in your application you are referencing an entity manager bean called emf
entityManagerFactoryRef = "emf"
You should define it. you can do it in your application context or in a
#Configuration Class.
For example you could define it this way :
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
......
</bean>

Spring FileNotFoundException

I wrote below 2 Java classes for learning Spring, but getting FileNotFoundException after running the code. Please help me to resolve this issue.
Is it not taking the path of the XML file?
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("xmlContext.xml");
//Resource resource=new ClassPathResource("xmlContext.xml");
//BeanFactory factory=new XmlBeanFactory(resource);
Student student = (Student)context.getBean("studentbean");
student.displayName();
}
}
2)
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayName() {
System.out.println("Name :"+name);
}
}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>

#Autowired field get null

I have this property-editor for my class Categoria and im trying to auto-wired it to the service, the problem its that the services keep getting a null value.
Also it seems like this is isolated or at least thats what i think, because i auto-wired a field of the same class at a controller, so i don't know whats going on, i already got an error like this, but at that time it didn't work at all .
Convertor
package com.carloscortina.paidosSimple.converter;
import java.beans.PropertyEditorSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.service.CategoriaService;
public class CategoriaConverter extends PropertyEditorSupport{
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private CategoriaService categoriaService;
#Override
public void setAsText(String categoria) {
logger.info(categoria);
Categoria cat = new Categoria();
cat = categoriaService.getCategoria(Integer.parseInt(categoria));
setValue(cat);
}
}
Service
package com.carloscortina.paidosSimple.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.carloscortina.paidosSimple.dao.CategoriaDao;
import com.carloscortina.paidosSimple.model.Categoria;
#Service
#Transactional
public class CategoriaServiceImpl implements CategoriaService{
#Autowired
private CategoriaDao categoriaDao;
#Override
public Categoria getCategoria(int id) {
// TODO Auto-generated method stub
return categoriaDao.getCategoria(id);
}
#Override
public List<Categoria> getCategorias() {
return categoriaDao.getCategorias();
}
}
Here It does Work
Controller
package com.carloscortina.paidosSimple.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;
#Controller
public class PersonalController {
private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);
#Autowired
private PersonalService personalService;
#Autowired
private UsuarioService usuarioService;
#Autowired
private CategoriaService categoriaService;
#RequestMapping(value="/usuario/add")
public ModelAndView addUsuarioPage(){
ModelAndView modelAndView = new ModelAndView("add-usuario-form");
modelAndView.addObject("categorias",categorias());
modelAndView.addObject("user", new Usuario());
return modelAndView;
}
#RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
public ModelAndView addingUsuario(#ModelAttribute Usuario user){
ModelAndView modelAndView = new ModelAndView("add-personal-form");
usuarioService.addUsuario(user);
logger.info(modelAndView.toString());
String message= "Usuario Agregado Correctamente.";
modelAndView.addObject("message",message);
modelAndView.addObject("staff",new Personal());
return modelAndView;
}
#RequestMapping(value="/personal/list")
public ModelAndView listOfPersonal(){
ModelAndView modelAndView = new ModelAndView("list-of-personal");
List<Personal> staffMembers = personalService.getAllPersonal();
logger.info(staffMembers.get(0).getpNombre());
modelAndView.addObject("staffMembers",staffMembers);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
public ModelAndView editPersonalPage(#PathVariable int id){
ModelAndView modelAndView = new ModelAndView("edit-personal-form");
Personal staff = personalService.getPersonal(id);
logger.info(staff.getpNombre());
modelAndView.addObject("staff",staff);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingPersonal(#ModelAttribute Personal staff, #PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.updatePersonal(staff);
String message = "Personal was successfully edited.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
public ModelAndView deletePersonal(#PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.deletePersonal(id);
String message = "Personal was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
private Map<String,String> categorias(){
List<Categoria> lista = categoriaService.getCategorias();
Map<String,String> categorias = new HashMap<String, String>();
for (Categoria categoria : lista) {
categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
}
return categorias;
}
#InitBinder
public void initBinderAll(WebDataBinder binder){
binder.registerCustomEditor(Categoria.class, new CategoriaConverter());
}
}
DAO
package com.carloscortina.paidosSimple.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
#Repository
public class CategoriaDaoImp implements CategoriaDao {
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public Categoria getCategoria(int id) {
Categoria rol = (Categoria) getCurrentSession().get(Categoria.class, id);
if(rol == null) {
logger.debug("Null");
}else{
logger.debug("Not Null");
}
logger.info(rol.toString());
return rol;
}
#Override
#SuppressWarnings("unchecked")
public List<Categoria> getCategorias() {
// TODO Auto-generated method stub
return getCurrentSession().createQuery("from Categoria").list();
}
}
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Enable transaction Manager -->
<tx:annotation-driven/>
<!-- DataSource JNDI -->
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" />
<!-- Session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:hibernateProperties-ref="hibernateProperties"
p:packagesToScan="com.carloscortina.paidosSimple.model" />
<!-- Hibernate Properties -->
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<context:annotation-config />
<context:component-scan base-package="com.carloscortina.paidosSimple,com.carlosocortina.paidosSimple.converter,com.carlosocortina.paidosSimple.service,com.carlosocortina.paidosSimple.dao" />
</beans>
Thanks in advance
Your are creating your PropertyEditor outside spring context using new operator (binder.registerCustomEditor(Categoria.class, new CategoriaConverter());) so service is not injected: follow the guide at this link to solve your problem.

Can spring framework override Annotation-based configuration with XML-based configuration?

Can spring framework override Annotation-based configuration with XML-based configuration? I need to change a dependency of a bean which is already defined via annotations and i am not the author of the bean.
i did not know that spring can mix configurations. here is the detailed and very useful example.
Bean1 is the actual bean we're configuring.
package spring;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
public class Bean1 {
private String naber;
#Autowired
#Qualifier("FireImpl1")
private Fire fire;
#PostConstruct
public void init() {
System.out.println("init");
getFire().fire();
}
#PreDestroy
public void destroy() {
System.out.println("destroy");
}
public void setNaber(String naber) {
this.naber = naber;
}
public String getNaber() {
return naber;
}
public void setFire(Fire fire) {
this.fire = fire;
}
public Fire getFire() {
return fire;
}
}
Fire is dependency interface
package spring;
public interface Fire {
public void fire();
}
and dummy implementation 1
package spring;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#Qualifier("FireImpl1")
public class FireImpl1 implements Fire {
public void fire() {
System.out.println(getClass());
}
}
and dummy implementation 2
package spring;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#Qualifier("FireImpl2")
public class FireImpl2 implements Fire {
public void fire() {
System.out.println(getClass());
}
}
config.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="spring" />
<bean id="bean1" class="spring.Bean1">
<property name="naber" value="nice" />
<property name="fire" ref="fireImpl2" />
</bean>
</beans>
and main class
package spring;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Spring {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring/config.xml");
applicationContext.registerShutdownHook();
Bean1 bean = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean.getNaber());
}
}
here is the output
init
class spring.FireImpl2
nice
destroy
Although annotation resolves dependency to FireImpl1, xml config overrided with FireImpl2.
very nice.
This should be OK. A Spring bean context allows you to redefine beans, with "later" definitions overriding "earlier ones". This should apply to XML-defined beans as well as annotation-defined beans, even if they're mixed.
For example, if you have
#Configuration
public class MyAnnotatedConfig {
#Bean
public Object beanA() {
...
}
}
<bean class="com.xyz.MyAnnotatedConfig"/>
<bean id="beanA" class="com.xyz.BeanA"/>
In this case, the XML definition of beanA should take precedence.

Resources