How use java config to create a inner bean? - spring

Spring Boot version:2.1.3.RELEASE,Spring Framework version:5.1.5.RELEASE.
Simple xml config like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="CustomerBean" class="io.github.ctlove0523.Customer">
<property name="person">
<bean class="io.github.ctlove0523.Person">
<property name="name" value="stackoverflow" />
<property name="address" value="address1" />
<property name="age" value="15" />
</bean>
</property>
</bean>
</beans>
how the java config would like?

Person.java
import org.springframework.beans.factory.annotation.Value;
public class Person {
#Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age + "]";
}
private String name;
private String address;
private Integer age;
public String getName() {
return name;
}
#Value("stackoverflow")
public void setName(String name) {
this.name = name;
}
#Value("address1")
public void setAddress(String address) {
this.address = address;
}
#Value("15")
public void setAge(Integer age) {
this.age = age;
}
}
CustomerBean.java
import org.springframework.beans.factory.annotation.Autowired;
public class CustomerBean {
Person person;
public Person getPerson() {
return person;
}
#Autowired
public void setPerson(Person person) {
this.person = person;
}
}
App.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook();
CustomerBean customerBean = context.getBean(CustomerBean.class);
System.out.println(customerBean.getPerson());
}
}
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
#Bean
public CustomerBean customerBean() {
return new CustomerBean();
}
#Bean
public Person person() {
return new Person();
}
}
Output :
Person [name=stackoverflow, address=address1, age=15]
Edit: Is this what you are looking for ??
Create beans from inner class using spring

Check the Spring documentation on Java configuration : https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
Depending on the code of your Person class, it would look something like this :
import io.github.ctlove0523.Customer;
#Configuration
public class AppConfig {
#Bean
public Customer customerBean() {
Customer myBean = new Customer();
// constructor or setter methods for Person
return myBean;
}
}

Related

Spring Aop ProxyFactoryBean and ProxyFactory and ClassCastException

When i use ProxyFactoryBean to get proxy object, I get a ClassCastException,but when i use ProxyFactory's getProxy() to get a proxy object, it works properly. I use Spring 4.x.
Definition of Two Beans,WaiterTest and Seller:
public class WaiterTest {
public void greetTo(String name){
System.out.println("waiter greet to " + name +"...");
}
public void serveTo(String name){
System.out.println("waiter serving " + name + "...");
}
}
public class Seller {
public void greetTo(String name){
System.out.println("seller greet to " +name + "...");
}
}
Definition of Advice:
public class GreetingBeforeAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object obj) throws Throwable{
System.out.println(obj.getClass().getName() + "." + method.getName());
String clientName =(String) args[0];
System.out.println("How are you! Mr." + clientName +".");
}
}
Definition of Advisor:
public class GreetingAdvisor extends StaticMethodMatcherPointcutAdvisor {
public boolean matches(Method method, Class clazz) {
return "greetTo".equals(method.getName());
}
public ClassFilter getClassFilter() {
return new ClassFilter() {
public boolean matches(Class clazz) {
return WaiterTest.class.isAssignableFrom(clazz);
}
};
}
}
Test Class:
public class TestGreetingBeforeAdvisor {
public static void main(String[] args) {
//method one: use by ProxyFactory
WaiterTest targetWaiterTest = new WaiterTest();
Seller targetSeller = new Seller();
GreetingBeforeAdvice advice = new GreetingBeforeAdvice();
GreetingAdvisor advisor = new GreetingAdvisor();
advisor.setAdvice(advice);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(targetWaiterTest);
pf.addAdvisor(advisor);
pf.setOptimize(true);
WaiterTest proxy = (WaiterTest) pf.getProxy();
proxy.greetTo("John");
proxy.serveTo("Tom");
ProxyFactory pf1 = new ProxyFactory();
pf1.setTarget(targetSeller);
pf1.addAdvisor(advisor);
Seller seller = (Seller) pf1.getProxy();
seller.greetTo("John");
System.out.println("=============");
//method two:Spring xml,use ProxyFactoryBean
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
WaiterTest test = (WaiterTest) ctx.getBean("waiterTest");
test .greetTo("John");
test .serveTo("John");
}
}
Beans.xml:
<bean id="waiterTarget" class="com.xxx.springaop.advisor.WaiterTest"/>
<bean id="sellerTarget" class="com.xxx.springaop.advisor.Seller"/>
<bean id="greetingAdvice1" class="com.xxx.springaop.advisor.GreetingBeforeAdvice"/>
<bean id="greetingAdvisor" class="com.xxx.springaop.advisor.GreetingAdvisor"
p:advice-ref="greetingAdvice1"/>
<bean id="parent" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean"
p:interceptorNames="greetingAdvisor"
p:proxyTargetClass="true"/>
<bean id="waiterTest" parent="parent" p:target-ref="waiterTarget"/>
<bean id="seller" parent="parent" p:target-ref="sellerTarget"/>
result:
com.xxx.springaop.advisor.WaiterTest.greetTo
How are you! Mr.John.
waiter greet to John...
waiter serving Tom...
seller greet to John...
=============
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to com.xxx.springaop.advisor.WaiterTest
at com.xxx.springaop.advisor.TestGreetingBeforeAdvisor.main(TestGreetingBeforeAdvisor.java:48)
Summarize:
WaiterTest proxy = (WaiterTest) pf.getProxy(); //success
WaiterTest test = (WaiterTest) ctx.getBean("waiterTest");//fail,ClassCastException
Why?
I was not able to reproduce your problem, but I did some refactoring on your code, and this works just fine for me. Maybe it helps you as well at least as a starting point..
Waiter.java
public class Waiter {
public void greetTo(String name) {
System.out.println("waiter greet to " + name + "...");
}
public void serveTo(String name) {
System.out.println("waiter serving " + name + "...");
}
}
GreetingBeforeAdvice.java
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class GreetingBeforeAdvice implements MethodBeforeAdvice {
#Override
public void before(Method method, Object[] args, Object obj) throws Throwable {
String clientName = (String) args[0];
System.out.println("How are you! Mr." + clientName + ".");
}
}
GreetingAdvisor.java
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import java.lang.reflect.Method;
public class GreetingAdvisor extends StaticMethodMatcherPointcutAdvisor {
public boolean matches(Method method, Class clazz) {
return "greetTo".equals(method.getName());
}
public ClassFilter getClassFilter() {
return new ClassFilter() {
public boolean matches(Class clazz) {
return Waiter.class.isAssignableFrom(clazz);
}
};
}
}
beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="waiter" class="Waiter"/>
<!-- Advisor Configuration -->
<bean id="greetingAdvice" class="GreetingBeforeAdvice"/>
<bean id="greetingAdvisor" class="GreetingAdvisor">
<property name="advice" ref="greetingAdvice"/>
</bean>
<bean id="waiterProxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>greetingAdvisor</value>
</list>
</property>
<property name="target" ref="waiter"/>
</bean>
</beans>
and finally App.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
final Waiter waiter = (Waiter) ctx.getBean("waiterProxyFactory");
waiter.greetTo("Koray Tugay");
waiter.serveTo("Koray Tugay");
}
}
The output for me is as follows using Spring 4.3.12:
How are you! Mr.Koray Tugay.
waiter greet to Koray Tugay...
waiter serving Koray Tugay...
I would say you have not configured 'target' object in you ProxyFactoryBean definition. A proxy cannot be created if it does not have a target.

autowired dao NullPointerException spring mvc + hibernate [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I'm trying to learn Spring MVC and Hibernate. When I try to run tests I have "Exception in thread "main" java.lang.NullPointerException".
public interface VacancyDAO
package pro.asfert.jobparser.dao;
public interface VacancyDAO {
void LoadDataBase(String query);
void FindVacancy(String queries);}
public class VacancyDAOImpl
package pro.asfert.jobparser.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class VacancyDAOImpl implements VacancyDAO {
#Autowired
private SessionFactory sessionFactory;
public void LoadDataBase(String query) {
sessionFactory.getCurrentSession().createQuery(query);
}
public void FindVacancy(String queries) {
if (queries.contains("По вашему запросу: ")) {
System.out.print(queries);
} else {
sessionFactory.getCurrentSession().createQuery(queries);
}
}
}
public interface VacancyService
package pro.asfert.jobparser.service;
public interface VacancyService {
void LoadDataBase();
void FindVacancy(String queries);
}
**public class VacancyServiceImpl**
package pro.asfert.jobparser.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pro.asfert.jobparser.dao.VacancyDAO;
import pro.asfert.jobparser.domain.Parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
#Service
public class VacancyServiceImpl implements VacancyService {
#Autowired
private VacancyDAO VacancyDAO;
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
/* deleted */
#Transactional
public void LoadDataBase() {
VacancyDAO.LoadDataBase(query);
}
#Transactional
public void FindVacancy(String queries) {
VacancyDAO.FindVacancy(sqlQuery);
}
application-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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:annotation-config />
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="ENVIRONMENT"/>
<context:component-scan base-package="pro.asfert.jobparser.dao"/>
<context:component-scan base-package="pro.asfert.jobparser.service"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value = "${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.databaseurl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class = "pro.asfert.jobparser.domain.Vacancy"></mapping>
</session-factory>
</hibernate-configuration>
Vacancy
package pro.asfert.jobparser.domain;
import javax.persistence.*;
#Entity
#Table(name = "Vacancies")
public class Vacancy {
public Vacancy() {
}
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column (name = "vacancy")
private String vacancy;
#Column (name = "salary")
private String salary;
#Column (name = "experience")
private String experience;
#Column (name = "education")
private String education;
#Column (name = "employer")
private String employer;
#Column (name = "details")
private String details;
#Column (name = "hr")
private String hr;
#Column (name = "url")
private String url;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVacancy() {
return vacancy;
}
public void setVacancy(String vacancy) {
this.vacancy = vacancy;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You're creating the service with new here:
public static void main(String[] args) {
VacancyServiceImpl vacancyService = new VacancyServiceImpl();
vacancyService.FindVacancy("test");
}
That way Spring is not involved and does not know anything about this object.
How to fix it:
register your dao and service as spring beans.
initialize the context and get the service from the context and call your method.
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml");
VacancyServiceImpl serv = ctx.getBean(VacancyServiceImpl.class);
serv.FindVacancy("test");

java.lang.NullPointerException on #Inject Dao

I'm trying to Inject a DAO into #Service component, but I get this error :
Exception in thread "main" java.lang.NullPointerException at
it.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24).
Fails to call the DAO which is null despite the annotation #Autowired
Below my code:
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- INIZIO IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<tx:annotation-driven/>
<context:property-placeholder location="classpath:hibernate.properties"/>
<context:component-scan base-package="it.cle.project.service.impl" />
<context:component-scan base-package="it.cle.project.dao.hbn" />
<context:component-scan base-package="it.cle.project.dao.hibernate" />
<!-- FINE IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<!-- INIZIO IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hibernate.properties"/>
</bean>
<!-- FINE IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<!-- INIZIO IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</prop>
</util:properties>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean "
p:dataSource-ref="dataSource" p:packagesToScan="it.cle.project.model"
p:hibernateProperties-ref="hibernateProperties" />
<!-- FINE IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
App.java
package it.cle.project;
import it.cle.project.model.TestEntity;
import it.cle.project.service.impl.TestEntityServiceImpl;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
System.out.println( "Hello World!" );
TestEntity testEntity = new TestEntity();
testEntity.setCampoUno("Campo Uno");
testEntity.setCampoDue("Campo Due");
testEntity.setEmail("email#test.it");
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
List<TestEntity> testEntitys = testEntityServiceImpl.getListTestEntity();
}
}
DAO Interface
package it.cle.project.dao;
import java.io.Serializable;
import java.util.List;
public interface Dao<T extends Object> {
void create(T t);
T get(Serializable id);
T load(Serializable id);
List<T> getAll();
void update(T t);
void delete(T t);
void deleteById(Serializable id);
void deleteAll();
long count();
boolean exists(Serializable id);
}
TestEntityDAO interface
package it.cle.project.dao;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityDao extends Dao<TestEntity> {
List<TestEntity> findByEmail(String email);
}
AbstractHbnDao Abstract class:
package it.cle.project.dao.hibernate;
import it.cle.project.dao.Dao;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
#Service
public abstract class AbstractHbnDao<T extends Object> implements Dao<T> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> domainClass;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
if (domainClass == null) {
ParameterizedType thisType =
(ParameterizedType) getClass().getGenericSuperclass();
this.domainClass =
(Class<T>) thisType.getActualTypeArguments()[0];
}
return domainClass;
}
private String getDomainClassName() {
return getDomainClass().getName();
}
public void create(T t) {
Method method = ReflectionUtils.findMethod(
getDomainClass(), "setDataCreazione",
new Class[] { Date.class });
if (method != null) {
try {
method.invoke(t, new Date());
} catch (Exception e) { /* Ignore */ }
}
getSession().save(t);
}
#SuppressWarnings("unchecked")
public T get(Serializable id) {
return (T) getSession().get(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public T load(Serializable id) {
return (T) getSession().load(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return getSession()
.createQuery("from " + getDomainClassName())
.list();
}
public void update(T t) { getSession().update(t); }
public void delete(T t) { getSession().delete(t); }
public void deleteById(Serializable id) { delete(load(id)); }
public void deleteAll() {
getSession()
.createQuery("delete " + getDomainClassName())
.executeUpdate();
}
public long count() {
return (Long) getSession()
.createQuery("select count(*) from " + getDomainClassName())
.uniqueResult();
}
public boolean exists(Serializable id) { return (get(id) != null); }
}
HbnTestEntityDao class DAO
package it.cle.project.dao.hbn;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.dao.hibernate.AbstractHbnDao;
import it.cle.project.model.TestEntity;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class HbnTestEntityDao extends AbstractHbnDao<TestEntity> implements TestEntityDao {
#SuppressWarnings("unchecked")
public List<TestEntity> findByEmail(String email) {
return getSession()
.getNamedQuery("findContactsByEmail")
.setString("email", "%" + email + "%")
.list();
}
}
TestEntityService interface service
package it.cle.project.service;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityService {
void createTestEntity(TestEntity testEntity);
List<TestEntity> getListTestEntity();
List<TestEntity> getTestEntityByEmail(String email);
TestEntity getTestEntity(Integer id);
void updateTestEntity(TestEntity testEntity);
void deleteTestEntity(Integer id);
}
TestEntityServiceImpl
package it.cle.project.service.impl;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.model.TestEntity;
import it.cle.project.service.TestEntityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class TestEntityServiceImpl implements TestEntityService {
#Autowired
private TestEntityDao testEntityDao;
public void createTestEntity(TestEntity testEntity) {
testEntityDao.create(testEntity);
}
public List<TestEntity> getListTestEntity() {
return testEntityDao.getAll();
}
public List<TestEntity> getTestEntityByEmail(String email) {
return testEntityDao.findByEmail(email);
}
public TestEntity getTestEntity(Integer id) {
return testEntityDao.get(id);
}
public void updateTestEntity(TestEntity testEntity) {
testEntityDao.update(testEntity);
}
public void deleteTestEntity(Integer id) {
testEntityDao.deleteById(id);
}
}
Any ideas?
Thanks.
Your TestServiceImpl should be spring managed bean and should be fetched from Spring application context (by injection or by explicit asking the context). As the component scanning is at work, your TestServiceImpl is already managed with Spring's own supplied name (com...TestServiceImpl becomes testServiceImpl). You can give it your name like
#Service("myTestServiceImpl")
The instead of creating the bean yourself you can query this named bean from application context and use it.
That's some wall of text. I stopped at:
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
You created an unmanaged bean. Spring has no control over that. Put TestEntityServiceImpl into your spring context.

How to define a Spring bean using annotation instead of XML?

I have defined in a xml config file:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
this works fine.
The bootsrap class :
public class Bootstrap {
#PostConstruct
public void onServerStart() {
System.out.println("PRINTSSSSSSSSSSSSSSSSSSS");
}
}
The method gets fired.
But how can I get rid of the xml part, and annotate bootstrap to be a bean instead?
I have
<mvc:annotation-driven />
<context:annotation-config />
and
<context:component-scan base-package="com.package" />
But I was wondering what the annotation used should be that replaces:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
I could not find anything about this online and in the spring docs :(
There's documentation regarding this; you'll want a stereotype annotation like #Component.
Stereotype bean annotations
this is a simple example that I have just made:
Main.java
package the.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext aac = new AnnotationConfigApplicationContext(Person.class, Phones.class);
Person person = aac.getBean(Person.class);
System.out.println(person.getPhones().getPhoneOne());
System.out.println(person.getPhones().getPhoneTwo());
System.out.println(person.getSurname());
System.out.println(person.getName());
System.out.println(person.getAge());
aac.close();
}
}
Person.java
package the.test;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
//you may use #ComponentScan("the.test") here and omit declaring
//"Phone.class" in the main method
public class Person {
private int age;
private String name;
private String surname;
private Phones phones;
public int getAge() {
return age;
}
#Value("33")
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
#Value("John")
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
#Value("Due")
public void setSurname(String surname) {
this.surname = surname;
}
public Phones getPhones() {
return phones;
}
#Resource
public void setPhones(Phones phones) {
this.phones = phones;
}
}
Phones.java
package the.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
public class Phones {
private String PhoneOne;
private String PhoneTwo;
public String getPhoneOne() {
return PhoneOne;
}
#Value("987654321")
public void setPhoneOne(String phoneOne) {
PhoneOne = phoneOne;
}
public String getPhoneTwo() {
return PhoneTwo;
}
#Value("123456")
public void setPhoneTwo(String phoneTwo) {
PhoneTwo = phoneTwo;
}
}
this is completely based on Spring Annotation and is made on spring framework 4.2.5
hope it helps.

Basic spring issue : using #Autowired

I have the following 2 objects: User and DomainUser
User.java:
package com.domain;
import java.io.Serializable;
#SuppressWarnings("serial")
public class User implements Serializable {
private long id = 0;
private String userName;
private String password;
public User() {
}
public User(long id) {
this.id = id;
}
public String toString() {
StringBuffer sb = new StringBuffer(256);
sb.append("[id : ").append(id).append(", ");
sb.append("userName : ").append(userName).append(", ");
sb.append("password : ").append(password).append("]");
return sb.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DomainUser.java
package com.domain;
import org.springframework.beans.factory.annotation.Autowired;
public class DomainUser {
#Autowired
private User user;
private String domainName;
public String toString() {
StringBuffer sb = new StringBuffer(255);
sb.append(user.toString()).append(", domainName : ").append(domainName);
return sb.toString();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}
I am trying to autowire the User object in to DomainUser by using #Autowired annotation. But when i run the test as below, the User object is not populated.
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="user" class="com.domain.User">
<constructor-arg value="#{1234}"/>
<property name="userName" value="somename" />
<property name="password" value="sompassword" />
</bean>
<bean id="domainUser" class="com.domain.DomainUser">
<property name="domainName" value="mysite" />
</bean>
</beans>
DomainUserTest.java
package com.domain.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.DomainUser;
public class DomainUserTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
DomainUser domainUser = (DomainUser) context.getBean("domainUser");
System.out.println(domainUser.toString());
}
}
If I autowire using the 'byType' in the autowiring attribute in the applicationContext.xml it works fine :
<bean id="domainUser" class="com.domain.DomainUser" autowire="byType">
<property name="domainName" value="mysite" />
</bean>
Can some one help me understand why doesnt #Autowired annotation produce the same result?
You need an AutowiredAnnotationBeanPostProcessor to handle the injection of #Autowired properties. You could place <context:annotation-config /> (you need to define the context-namespace in your xml) or just define the post processor as a bean in your xml:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
See for example here for details.

Resources