Java spring 'Hello World' example couldn't compile - java

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?

Related

CannotLoadBeanClassException when try to get a bean from applicationContext.xml

i have just started a course about Spring framework and i am struggling getting over this exceiption:
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [TrackCoach] for bean with name 'myCoach' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: TrackCoach
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1476)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:682)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:649)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1604)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1080)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:859)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at com.love2code.springdemo.HelloSpringApp.main(HelloSpringApp.java:9)
This is my main class:
package com.love2code.springdemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringApp {
public static void main(String[] args) {
//load the spring configuration file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//retrieve bean from spring container
Coach theCoach = context.getBean("myCoach", Coach.class);
//call methods on the bean
System.out.println(theCoach.getDailyWorkout());
//close the context
context.close();
}
}
My TrackCoach class:
package com.love2code.springdemo;
public class TrackCoach implements Coach {
#Override
public String getDailyWorkout() {
return "Smoke 2 bl's";
}
}
And 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"
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">
<!-- Define your beans here -->
<bean id="myCoach" class="com.luv2code.springdemo.TrackCoach">
</bean>
</beans>
Could someone help me out with this please?

aop:aspectj-autoproxy has worked bad at applicationContext

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.

spring framework null pointer exception

Trying to autowire Spring bean with property, but still getting NPE. Snippets:
INFO: Loading XML bean definitions from class path resource [autoWireByName.xml]
Exception in thread "main" today do push-ups for 30 mins
java.lang.NullPointerException
at com.springAutoWireByName.KabadiCoach.getFortune(KabadiCoach.java:23)
at com.springAutoWireByName.AutoWireByName.main(AutoWireByName.java:13)
KabadiCoach.java
package com.springAutoWireByName;
public class KabadiCoach {
private SadFortune sadFortune;
/*public KabadiCoach(){
System.out.println("inside default Constructor");
}*/
public String getDailyWorkout()
{
return "today do push-ups for 30 mins";
}
public void setSadFortune(SadFortune fortune) {
sadFortune = fortune;
}
public String getFortune() {
return sadFortune.getSadFortune();
}
}
SadFortune.java
package com.springAutoWireByName;
public class SadFortune {
public String getSadFortune()
{
System.out.println();
return "your day wont be good enough Sorry!!!";
}
}
<?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">
<!-- bean definitions here -->
<bean name="Fortune" class="com.springAutoWireByName.SadFortune">
</bean>
<bean id="myCoach" class="com.springAutoWireByName.KabadiCoach" autowire="byName" />
<!-- this is just a prototype to define actual just make use of this file-->
</beans>
main
package com.springAutoWireByName;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AutoWireByName {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =new ClassPathXmlApplicationContext("autoWireByName.xml");
KabadiCoach co = context.getBean("myCoach",KabadiCoach.class);
System.out.println(co.getDailyWorkout());
System.out.println(co.getFortune());
}
}
after running the above code I am getting the error message as listed and when I change the method to static
public static String getSadFortune()
{
System.out.println();
return "your day wont be good enough Sorry!!!";
}
In class 2 I got the desired output. Why?
Basically the SadFortune member is still null, which is why it works if the getSadFortune() method will be made static.
Until now you only tell Spring to instantiate a Fortune bean and a KabadiCoach, but you have to tell Spring that some members in the KabadiCoach need to be autowired too.
Try this in your Spring configuration file:
<bean id="fortune" class="com.springAutoWireByName.SadFortune"></bean>
<bean id="myCoach" class="com.springAutoWireByName.KabadiCoach" autowire="byName">
<property name="fortune" ref="fortune" />
</bean>
EDIT: Sorry, overread the autowire="byName" attribute. In this case you probably just have write the name in lower case.
<bean id="fortune" class="com.springAutoWireByName.SadFortune"/>
<bean id="myCoach" class="com.springAutoWireByName.KabadiCoach" autowire="byName"/>

Spring set java.io.File property use java.lang.String bean

I found a strange thing while learning Spring tech.
I inject a java.lang.String type bean into a bean property which type is java.io.File, but the program still runs normally.
I want to know
What happened internally?
Is it a valid usage or a trick?
Here is the spring configuration file stringtofile.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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
default-lazy-init="true">
<bean id="file_str"
class="java.lang.String"
c:_="C:\tmp\test.hi"/>
<bean id="file"
class="stringtofile.FileWrapper"
p:file-ref="file_str"/>
</beans>
Here is my test classes.
package stringtofile;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.File;
public class FileWrapper {
File file;
public File getFile() {
return file;
}
public FileWrapper setFile(File file) {
this.file = file;
return this;
}
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("stringtofile.xml");
FileWrapper fileWrapper =
(FileWrapper) ctx.getBean("file");
System.out.println(fileWrapper.getFile());
}
}
It is done by the PropertyEditors in your case the FileEditor
Check the documentation here for more details: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

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.

Categories