AOP spring using #Before get java.lang.StackOverflowError - spring

I am trying to learn AOP spring. so I have installed AspectJ plug in and created AspectJ project in Luna eclipse and here is snapshot of Project Explore:
[Project Explore][1] [1]: https://i.stack.imgur.com/el0TZ.jpg
and here is my codes:
AopMain.java
package org.koushik.javabrains;
import org.koushik.javabrains.service.ShapeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AopMain {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("spring.xml");
ShapeService shapeService = ctx.getBean("shapeService",ShapeService.class);
System.out.println(shapeService.getCircle().getCircleName());
}
}
LoggingAspect.java
package org.koushik.javabrains.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class LoggingAspect {
#Before( "allCircleMethod()")
public void loggingAdvice(JoinPoint joinPoint){
System.out.println(joinPoint.toString());
}
//#Before("args(name)")
//public void stringArgumentMethods(String name){
// System.out.println("name: "+name);
//}
#Pointcut("execution(* get*())")
public void allGetters(){}
#Pointcut("within(org.koushik.javabrains.model.Circle)")
public void allCircleMethod(){}
}
Circle.java
package org.koushik.javabrains.model;
public class Circle {
private String circleName;
public String getCircleName() {
return circleName;
}
public void setCircleName(String circleName) {
this.circleName = circleName;
}
}
Triangle.java
package org.koushik.javabrains.model;
public class Triangle {
private String triangleName;
public String getTriangleName() {
return triangleName;
}
public void setTriangleName(String triangleName) {
this.triangleName = triangleName;
}
}
ShapeServices.java
package org.koushik.javabrains.service;
import org.koushik.javabrains.model.Circle;
import org.koushik.javabrains.model.Triangle;
public class ShapeService {
private Circle circle;
private Triangle triangle;
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
}
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean name="triangle" class="org.koushik.javabrains.model.Triangle">
<property name="name" value ="Triangle name"></property>
</bean>
<bean name="circle" class="org.koushik.javabrains.model.Circle">
<property name="name" value ="Circle Name"></property>
</bean>
<bean name="shapeService" class="org.koushik.javabrains.service.ShapeService" autowire="byName"/>
<bean name ="loggingAspect" class ="org.koushik.javabrains.aspect.LoggingAspect"/>
</beans>
The code works fine without using in LoggingAspect.java:
#Before("args(name)")
public void stringArgumentMethods(String name){
System.out.println("name: "+name);
}
but when I add it, I will get the java.lang.stackOverflowError:
Exception in thread "main" java.lang.StackOverflowError
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
at org.koushik.javabrains.aspect.LoggingAspect.stringArgumentMethods(LoggingAspect.java)
can anyone tell me why this happend? how can solve it?

From java docs,
StackOverFlowError - What:
Thrown when a stack overflow occurs because an application recurses
too deeply.
This means , memory (stack) is full and have no space to store further.
Why:
In most cases this situation is created by recursive/deep calling of methods.
In Your case, #Before("args(name)") - this line tries to find ALL methods with the argument "name", it find itself which leads to recursive call and the stackoverflow error.Because stringArgumentMethods(String name) also having the argument name
public void stringArgumentMethods(String name){
System.out.println("name: "+name);
}
How to Solve:
Either rewrite your AspectJ expression - #Before("args(name)")
Or
rename the argument like stringArgumentMethods(String name123)

Related

NullPointerException while using #Autowired in maven webapp

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!

Spring: A bean's init-method is being triggered when invoking other beans

I'm currently experimenting on bean callback methods and noticed that if I define callback methods for one bean, these methods are also called on other beans.
I have a classes named x.HelloWorld (no callbacks) and y.HelloWorld (has init and destroy callback methods).
HelloWorld.java:
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
HelloWorld2.java:
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
public void init() {
System.out.println("Bean is going through init.");
}
public void destroy() {
System.out.println("Bean will destroy now.");
}
}
x.MainApp.java:
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
y.MainApp.java:
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld2");
obj.getMessage();
context.registerShutdownHook();
}
}
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" 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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="helloWorld" class="x.HelloWorld">
<property name="message" value="Hello World (1)" />
</bean>
<bean id="helloWorld2" class="y.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World (2)" />
</bean>
</beans>
Results:
Running y.MainApp (works as expected):
Bean is going through init.
Your Message : Hello World (2)
Bean will destroy now.
Running x.MainApp (the init callback of x.HelloWorld is triggered by y.HelloWorld. Confused of this one.. any help is very much appreciated...)
Bean is going through init.
Your Message : Hello World (1)
Please modify your init method like this:
public void init() {
System.out.println("Bean with message '"+ message +"' is going through init.");
}
You will see that all beans are initialized at startup and that the message you see actually comes from the class with the init method.
If you don't want this behavior you can use lazy init:
<bean id="helloWorld2" class="y.HelloWorld"
init-method="init" destroy-method="destroy" lazy-init="true">

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>

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.

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