aop:aspectj-autoproxy has worked bad at applicationContext - java

I'm a beginner in spring,I have a problem with using aop:aspectj-autoproxy at applicationContext.It has confused me.
There is directory image:
directory
The test codes is very simple,I have omited 'import' statement
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"
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="schema2.*" />
<aop:aspectj-autoproxy />
</beans>
Logger.java:
#Aspect
#Component
public class Logger{
#Before("execution(* schema2.manager.*(..))")
public void before(JoinPoint joinPoint){
System.out.println("The Method: " + joinPoint.getSignature().getName());
}
}
BookShopDao.java:
public interface BookShopDao{
int findBookPriceByIsbn(String isbn);
void updateBookStock(String isbn) throws RuntimeException;
void updateUserAccount(String username, int price);
}
BookShopDaoImpl.java:
#Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao{
#Override
public int findBookPriceByIsbn(String isbn) {
return 0;
}
#Override
public void updateBookStock(String isbn) throws RuntimeException {
}
#Override
public void updateUserAccount(String username, int price) {
}
}
BookShopService.java:
public interface BookShopService {
void purchase(String book_isbn, String user_name);
}
BookShopServiceImpl.java:
#Service("bookShopService")
public class BookShopServiceImpl implements BookShopService{
#Override
public void purchase(String book_isbn, String user_name) {
}
}
Start.java
public class Start {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookShopService server = (BookShopService) context.getBean("bookShopService");
server.purchase("123", "John");
}
}
problem:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookShopDao' defined in file [C:\Users\qiang\Desktop\spring\spring2\out\production\spring2\schema2\manager\BookShopDaoImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: schema2.manager [Xlint:invalidAbsoluteTypeName]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookShopDao' defined in file [C:\Users\qiang\Desktop\spring\spring2\out\production\spring2\schema2\manager\BookShopDaoImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: schema2.manager [Xlint:invalidAbsoluteTypeName]
But if I delete
aop:aspectj-autoproxy
which at applicationContext.xml,it become no problem,and it have losed #before logging

I've found answer,I haven't checked carefull...
#Before("execution(* schema2.manager.*(..))") should be changed to #Before("execution(* schema.manager*.*(..))")
And my project lib has been imported 'aspectj/lib' that whole directory, I also dont't konw why it cause the problem,it's weird.

Related

Spring #Autowire when using multi-level interfaces

I want to find a solution to configure my spring to support multi-level inheritance of interfaces.The considered scenario is as follow:
public class MainClass {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) ctx.getBean("textEditor");
te.spellCheck();
}
//--------------------
#Component
public class TextEditor {
#Autowired
private SpellChecker1 spellChecker;
public void spellCheck() {
spellChecker.checkSpelling();
}
}
//--------------------
public interface SpellChecker1 extends SpellChecker2{
}
//--------------------
public interface SpellChecker2 {
public void checkSpelling();
}
//--------------------
#Service
public class SpellCheckerImpl implements SpellChecker2 {
public SpellCheckerImpl() {
System.out.println("Inside SpellChecker constructor.");
}
#Override
public void checkSpelling() {
System.out.println("Inside checkSpelling.");
}
}
//--------------------
Also, my Beans.xml file is contain:
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.mycompany.test"/>
<bean id="textEditor" class="com.mycompany.test.TextEditor" >
</bean>
</beans>
//The following error is issued when running the the MainClass
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'textEditor': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.test.SpellChecker1 com.mycompany.test.TextEditor.spellChecker; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mycompany.test.SpellChecker1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

Java spring 'Hello World' example couldn't compile

As a HelloWorld example, in my spring Beans.xml file, I have:
<?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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
The main file:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
The class file:
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
The error seems like this:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloWorld' defined in class path resource [Beans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.tutorialspoint.HelloWorld]: Is the constructor accessible?; nested exception is java.lang.IllegalAccessException: class org.springframework.beans.BeanUtils (in module spring.beans) cannot access class com.tutorialspoint.HelloWorld (in module HelloSpring) because module HelloSpring does not export com.tutorialspoint to module spring.beans
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1320)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at spring.beans#5.2.5.RELEASE/org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at spring.context#5.2.5.RELEASE/org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at HelloSpring/com.tutorialspoint.MainApp.main(MainApp.java:8)
Other folks on this site got the same problem, and I've looked at it. However, I've tried all the answers provided but none of them solved my issue. I've used several versions of the path inside and there's no empty line above the first line of my Beans.xml. What's the problem here?

No bean named is defined Exception

package com.mkyong.output;
IOutputGenerator.java
public interface IOutputGenerator
{
public void generateOutput();
}
package com.mkyong.output;
OutputHelper.java
#Component
public class OutputHelper {
#Autowired
IOutputGenerator outputGenerator;
public void generateOutput() {
outputGenerator.generateOutput();
}
/*//DI via setter method
public void setOutputGenerator(IOutputGenerator outputGenerator) {
this.outputGenerator = outputGenerator;
}*/
}
package com.mkyong.output.impl;
CsvOutputGenerator.java
#Component
public class CsvOutputGenerator implements IOutputGenerator {
public void generateOutput() {
System.out.println("This is Csv Output Generator");
}
}
SpringBeans.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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.mkyong" />
</beans>
i am getting this exception Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'OutputHelper' is defined
even though i have marked OutputHelper as component.
I have changed
OutputHelper output = (OutputHelper) context.getBean("OutputHelper");
to
OutputHelper output = (OutputHelper) context.getBean("outputHelper");
and it worked.
Hi i think you haven't added following in your Spring XML configuration
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<mvc:annotation-driven/>
you need to see top exception and read the whole line.
i guess there have a exception is nested exception just like #Autowired xxxxxx,meas autowired fail.
i have notice this:
#Autowired
IOutputGenerator outputGenerator;
and
#Component
public class CsvOutputGenerator implements IOutputGenerator
so, in the default, class name is used to #Autowired,you can rewrite to
#Autowired
IOutputGenerator csvOutputGenerator;
notice:
"csvOutputGenerator" first letter is lowercase
the easier option would be to enable annotations in beans already registered in the application context, means that you can just use #Autowired instead of getting manually all beans with context.getBean()
just add this line to your SpringBeans.xml
<context:annotation-config>
if you really want to understand what you are doing reading this could help.

BeanCreationException : Injection of autowired dependencies failed

I have 2 classes in 2 different projects, and I have some difficulties to autowire a field.
In project pack, I have this Computation class :
package fr.aaa;
#Component
public class Computation {
#Autowired
#Qualifier("curveDAO")
CurveAccess curveDAO;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
}
}
In project db, I have this CurveAccess interface :
package com.bbb
public interface CurveAccess {
// some methods
}
implemented by a CurveDAO class :
package com.bbb.impl
#Repository("curveDAO")
#Transactional("cvaTxManager")
public class CurveDAO implements CurveAccess {
// some methods
}
My applicationContext.xml file from pack project :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xmlns:security="http://www.springframework.org/schema/security" xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
<import resource="classpath:spring/persistence.xml"/>
<context:annotation-config />
<context:component-scan base-package="fr.aaa.*, com.bbb.*"/>
<util:properties id="jdbcProps" location="jdbc.properties" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configuration.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
When running, I have this exception :
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Computation': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.bbb.CurveAccess fr.aaa.Computation.curveDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.bbb.CurveAccess] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=curveDAO)}
How can I solve this problem ?
Actually, your code works perfectly fine:
#SpringBootApplication
public class So21481801Application implements CommandLineRunner {
public interface CurveAccess {
String hello();
}
#Repository("curveDAO")
public class CurveDAO implements CurveAccess {
#Override
public String hello() {
return "Hello";
}
}
#Repository("curveDAOWorld")
public class CurveDAOWorld implements CurveAccess {
#Override
public String hello() {
return "World";
}
}
#Autowired
#Qualifier("curveDAO")
CurveAccess curveDAO;
#Autowired
#Qualifier("curveDAOWorld")
CurveAccess curveDAOWorld;
#Override
public void run(String... args) {
System.out.println(curveDAO.hello());
System.out.println(curveDAOWorld.hello());
}
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(So21481801Application.class, args);
context.close();
}
}
Probably you have some problem on how you are using the component-scan configuration on XML and the Java annotations. Mix them is not a good idea.
You need a class that implements CurveAccess interface
#Component
public class CurveAccessImpl implements CurveAccess {
//methods
}
Also remove Qualifier from curveDao in Computation bean since there is no such bean with id curveDao.
#Autowired
CurveAccess curveDAO;

#Qualifier Annotation in Spring is not working

I have just learnt Spring Framework and have been using Spring 2.5 for this learning. I have created three beans with these classes
Food.java
package com.spring.danipetrick;
public interface Food {
void ingredients();
}
NasiGoreng.java
package com.spring.danipetrick;
public class NasiGoreng implements Food {
public NasiGoreng() {
}
public void ingredients() {
System.out.println("Rice, Coconut oil, Egg, Crackers");
}
#Override
public String toString() {
return "Nasi Goreng";
}
}
Rendang.java
package com.spring.danipetrick;
public class Rendang implements Food {
public void ingredients() {
System.out.println("Beef, Coconut milk, spices");
}
#Override
public String toString() {
return "Rendang";
}
}
PecintaKuliner.java
package com.spring.danipetrick;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class PecintaKuliner {
#Autowired
#Qualifier("nasigoreng")
private Food food;
#Autowired
public void setFood(Food food) {
this.food = food;
}
public Food getFood() {
return this.food;
}
public void sayMaknyus() {
System.out.println(food.toString() + " memang maknyus...");
}
}
Xml configuration, qualifier-test.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="bondan" class="com.spring.danipetrick.PecintaKuliner">
</bean>
<bean id="rendang" class="com.spring.danipetrick.Rendang"/>
<bean id="nasigoreng" class="com.spring.danipetrick.NasiGoreng" />
</beans>
Finally, class with main method is QualifierTestMain.java:
package com.spring.danipetrick;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QualifierTestMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/qualifier-test.xml");
PencintaKuliner bondan = (PencintaKuliner)context.getBean("bondan");
bondan.sayMaknyus();
}
}
When I run this project, I have an error like this
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
unique bean of type [com.spring.danipetrick.Food] is defined: expected
single matching bean but found 2: [rendang, nasigoreng]
Why #Qualifier annotation is not working in my case?
Both your method and field are annotated with #Autowired. As such, Spring will try to inject both. On one of the runs, it will try to inject
#Autowired
#Qualifier("nasigoreng")
private Food food;
which will work because the injection target is qualified.
The method however
#Autowired
public void setFood(Food food) {
this.food = food;
}
does not qualify the injection parameter so Spring doesn't know which bean to inject.
Change the above to
#Autowired
public void setFood(#Qualifier("nasigoreng") Food food) {
this.food = food;
}
But you should decide one or the other, field or setter injection, otherwise it is redundant and may cause errors.
I tried with Spring 4.2.4. Problem resolved just by adding
<context:annotation-config /> in configuration file.
Try only removing #Autowired from setFood() in PecintaKuliner
like
#Autowired
#Qualifier("nasigoreng")
private Food food;
public void setFood(Food food) {
this.food = food;
}
Try removing you constructor from the NasiGoreng class. It worked for me.
For others facing issue in Spring 5 -- Use xmlns based configuration..
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>

Categories