Failed to load ApplicationContext while running test cases - java

when i am running my spring integration junit class i am getting above exception.
here is my class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BpmControllerTest {
#Autowired
private BpmProcessorDaoImplTest bpmProcessorDao;
#Test
public void testRun() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
List<User>user=bpmProcessorDao.testRead();
Assert.assertEquals(0,user.size());
}
}
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
here is my stack trace..
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 37 more
can any body please tell me how to write this line
#ContextConfiguration(locations = "classpath:applicationContext.xml")
some places in google i found like this
#ContextConfiguration(locations = "classpath:**/applicationContext.xml")
what is the difference of these two
and when i am writing this line with stars i am getting different exception
here is my stack trace.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tcs.test.dao.BpmProcessorDaoImplTest] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
and one thing that my application is only dynamic web project no maven,no ant .
can any body please tell me how to run my test cases successfully..
here is my applicationContext.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
">
<tx:annotation-driven />
<tx:jta-transaction-manager/>
<context:component-scan base-package="com.tcs.test" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.19.8.159:1521/OIM.itba.gov.in" />
<property name="username" value="AppDB"></property>
<property name="password" value="AppDB"></property>
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="runScheduler" class="com.tcs.controller.BpmControllerTest" />
<task:scheduled-tasks>
<task:scheduled ref="runScheduler" method="testRun" cron="0 0/1 * * * ?" />
</task:scheduled-tasks>
</beans>
all my test java files in side test source folder.
and all the files in side the package's which prefix is com.tcs.test
here is my daoImpl class
package com.tcs.test.dao;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import com.tcs.controller.BPMConstants;
import com.tcs.controller.User;
#Repository
public class BpmProcessorDaoImplTest implements BpmProcessorDaoTest{
private static final Logger logger=Logger.getLogger(BpmProcessorDaoImplTest. class);
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
#Test
public void testWrite() {
}
#Test
public void testUpdateStatus() {
}
#Test
public List<User> testRead() {
String query=null;
List<User>users=null;
try{
// jdbcTemplate.setDataSource(dataSource);
// query=messageSource.getMessage(BPMConstants.QUERY,null,Locale.US);
query="select taskoutcome,seqNo,hash_mapdata,userid,status,taskId from com_tt_bpm_batch , "
+ "wftask where status='ACTIVE' and request_id=instanceid and state='ASSIGNED'";
logger.info("query");
jdbcTemplate.setFetchSize(20);
users=jdbcTemplate.query(query, new ResultSetExtractor<List<User>>(){
List<User> userList = new ArrayList<User>();
#SuppressWarnings("unchecked")
#Override
public List<User> extractData(ResultSet rs) throws SQLException,DataAccessException {
while(rs.next()){
logger.info("fetching records from db");
User user = new User();
user.setTaskOutcome(rs.getString(BPMConstants.TASK_OUTCOME));
user.setUserId(rs.getString(BPMConstants.USER_ID));
user.setStatus(rs.getString(BPMConstants.STATUS));
user.setTaskId(rs.getString(BPMConstants.TASK_ID));
user.setSeqNo(rs.getLong(BPMConstants.SEQ_NO));
user.setUserComment("nothing");
Blob blob=rs.getBlob(BPMConstants.HASH_MAPDATA);
try{
if(blob!=null && !blob.equals("")){
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
ByteArrayInputStream bos = new ByteArrayInputStream(blobAsBytes);
ObjectInputStream out=null;
out = new ObjectInputStream(bos);
HashMap<String, Object> map=null;
map = (HashMap<String, Object>)out.readObject();
user.setMap(map);
}
userList.add(user);
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from blob "+e.getStackTrace());
}
}
return userList;
}
});
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from db "+e.getStackTrace());
}
return users;
}
}

1)
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
The web-inf folder is not (without hacks and problems) accessabel while running the tests.
So the short and easy solution is to put that spring config files in:
(if you use maven): src\main\resources
(if you do not use maven): your java source file root folder
(if you do not use maven but eclipse): create an extra folder (for example resources), put the files in that folder, and then make this folder a eclipse source folder (right click that folder in the package explorer and then choose "Build Path" / "Use as Source Folder")
2)
your BpmProcessorDaoImplTest does not look like a valid test for me.
Either it is a Test case - then its methods have #Test annotations and the class itself have the #ContextConfiguration configuration that points to your configuration file. Or is is a Repository then it has a #Repository annotation and not #Test or #ContextConfiguration. annotations. But I never saw a class that mixed this.
So try this:
#ContextConfiguration("classpath:applicationContext.xml")
#Transactional //make your tests run in an transaction that gets rolled back after the test
public class BpmProcessorDaoImplTest {
/** Class under test */
#Autowired
private BpmProcessorDao dbmProcessorDao;
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
//just to make the example test usefull
#PersistenceContext
private EntityManager em
#Test
public void testWrite() {
DbmProcessor entity = ...;
...
this.dbmProcessorDao.save();
...
em.flush(); //make sure that every is saved before clear
em.clear(); //clear to make read(id) read the entity from the database but not from l1-cache.
int id = entity.getId();
...
DbmProcessor reloadedEntity = this.dbmProcessorDao.read(id);
//getName is just an example
assertEquals(entity.getName(), dbmProcessorDao.getName());
}
}

This will occure when applicationContext.xml cannot be found in class path
Possible solutions :
add directory containing applicationContext.xml to classpath.
give relative path of applicationContext.xml
give absolute path of applicationContext.xml
If 3rd solution worked for you would mean that applicationContext.xml was not in classpath.

Related

I am trying Spring MVC and when I add #Autowired in my controller class I get following error:

<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"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:component-scan base-package="com.packt.webstore.domain" />
<context:annotation-config></context:annotation-config>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Webstore"></property>
<property name="username" value="root"></property>
<property name="password" value="password"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productController': Unsatisfied
dependency expressed through field 'productRepository'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productRepositoryImpl': Unsatisfied
dependency expressed through method 'setDataSource' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'javax.sql.DataSource' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
package com.packt.webstore.domain.repository.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
#Repository
public class ProductRepositoryImpl implements ProductRepository {
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
private void setDataSource(DataSource dataSource) {
this.jdbcTemplate=new NamedParameterJdbcTemplate(dataSource);
}
#Override
public List<Product> getAllProducts() {
Map<String, Object>params=new HashMap<String,Object>();
List<Product>result=jdbcTemplate.query("SELECT * FROM PRODUCTS", params, new ProductMapper());
return result;
}
private static final class ProductMapper implements org.springframework.jdbc.core.RowMapper<Product> {
public Product mapRow(ResultSet rs,int rownum) throws SQLException{
Product product=new Product();
product.setName(rs.getString("name"));
return product;
}
}
}
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven enable-matrix-variables="true"></mvc:annotation-driven>
<context:component-scan base-package="com.packt"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
package com.packt.webstore.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.domain.repository.ProductRepository;
#Controller
public class ProductController {
#Autowired
private ProductRepository productRepository;
#RequestMapping("/products")
public String list(Model model) {
model.addAttribute("products",productRepository.getAllProducts());
return "products";
}
}
it looks like you din't configure data-source in xml file
try to add below configuration in xml file
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/yourdbname" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
You need to define DataSource bean in your XML file then only use can use #Autowired annotation to configure that bean or you can use #Autowired annotation in the following way:
#Autowired
private NamedParameterJdbcTemplate jdbcTemplate;

Neo4j with Spring: No bean named 'getSessionFactory' available

I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
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/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here

How To enhance The Callback handler CXF Interceptor method

I made a WSS4JInInterceptor in a spring bean configuration file as follows
<?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:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxws:endpoint id="book"
implementor="net.ma.soap.ws.endpoints.IBookEndPointImpl" address="/bookAuth">
<jaxws:inInterceptors>
<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor"></bean>
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken" />
<entry key="passwordType" value="PasswordText" />
<entry key="passwordCallbackClass" value="net.ma.soap.ws.service.ServerPasswordCallback"></entry>
</map>
</constructor-arg>
</bean>
</jaxws:inInterceptors>
</jaxws:endpoint>
</beans>
The ServerPasswordCallBack.java looks like the following
package net.ma.soap.ws.service;
import java.io.IOException;
import java.util.ResourceBundle;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
public class ServerPasswordCallback implements CallbackHandler {
private static final String BUNDLE_LOCATION = "zuth";
private static final String PASSWORD_PROPERTY_NAME = "auth.manager.password";
private static String password;
static {
final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_LOCATION);
password = bundle.getString(PASSWORD_PROPERTY_NAME);
}
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
pc.setPassword(password);
}
}
With the password verification, everything work just fine.
I'd like to know if there's any other way to enhance the handle(Callback) method to make it more sophisticated so it would be able to check more than just one parameter, for example if i can make it check an access token, it would be much more better.
the password property is defined in zuth_fr_FR.properties file as follows
auth.manager.password=najah
If you want to do some custom validation on your username and token (such as verify against a directoryservice using LDAP or something similar) you can write your own custom UsernameTokenValidator overriding verifyPlaintextPassword(UsernameToken usernameToken) of UsernameTokenValidator and hook it up to your WSS4JInInterceptor adding the following to your bean definition
<property name="wssConfig">
<ref bean="usernameTokenWssConfig"/>
</property>
And add the referenced class to your codebase:
#Component("usernameTokenWssConfig")
public class usernameTokenWssConfigWSSConfig {
public usernameTokenWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, new CustomUsernameTokenValidator());
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

declaration can be found for element 'context:property-placeholder'. Spring 4

I browsed around 30 webpages and 50 articles about this and it's still not working.
Here is my code its really simple I'm only a Spring beginner.
App.java
package com.procus.spring.simple.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* #author procus
*/
public class App {
public static void main(String[] args) {
ApplicationContext con = new ClassPathXmlApplicationContext("SpringBeans.xml");
SampleSimpleApplication sam = (SampleSimpleApplication) con.getBean("sam");
sam.run(args);
}
}
SampleSimpleApplication.java
package com.procus.spring.simple.simple;
import com.procus.calculator.basic.BasicCalculator;
import com.procus.spring.simple.simple.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = BasicCalculator.class)
public class SampleSimpleApplication implements CommandLineRunner {
// intentional error
#Autowired
BasicCalculator calculator;
// Simple example shows how a command line spring application can execute an
// injected bean service. Also demonstrates how you can use #Value to inject
// command line args ('--name=whatever') or application properties
#Autowired
private HelloWorldService helloWorldService;
public SampleSimpleApplication() {
}
#Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
HelloWorldService.java
package com.procus.spring.simple.simple.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
#Component
#Configuration
#PropertySource(value = { "classpath:application.properties" })
public class HelloWorldService {
#Value("${app.name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
SpringBeans.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.0.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:property-placeholder location="classpath*:application.properties"/>
<bean id="DBProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<value>classpath*:application.properties</value>
</property>
</bean>
<bean id="sam" class="com.procus.spring.simple.simple.SampleSimpleApplication"/>
<bean id="serv" class="com.procus.spring.simple.simple.service.HelloWorldService">
<property name="name" value="Jano" />
</bean>
<bean id="calc" class="com.procus.calculator.basic.BasicCalculator">
<constructor-arg value="1.0"/>
</bean>
</beans>
And in resources folder is my application.properties file which contains only app.name=Phil
Exception in thread "main"
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
Line 12 in XML document from class path resource [SpringBeans.xml] is
invalid; nested exception is org.xml.sax.SAXParseException;
lineNumber: 12; columnNumber: 81; cvc-complex-type.2.4.c: The matching
wildcard is strict, but no declaration can be found for element
'context:property-placeholder'.
I really tried most of solutions which I found at stackoverflow and few other forums. I`m really new in spring and I will appreciate any help.
In your springbeans.xml you've specified the location as "classpath*:application.properties" classpath with a * whereas in your HelloWorldService.java you've specified the location as "classpath:application.properties". There is a discrepancy in the two locations.
Besides the problem lies in the SpringBeans.xml schema declaration. It is incorrect & incomplete.
After the context declaration http://www.springframework.org/schema/context/spring-context-4.0.xsd is missing
check this this & this
Ideally it should be
<?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"
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">
I am unable to comment -
What i see is you are writing : <context:property-placeholder location="classpath*:application.properties"/>
Why is there a * after classpath.
It should work with - <context:property-placeholder location="classpath:application.properties"/>
Else -
You can use -
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
In you Heloworld bean
<bean id="helloworld" class ="package.HelloWorldService" >
<property name="name" value="${app.name}" />
</bean>

NoSuchBeanDefinitionException while using #Configuration

I have weird situation.
I tried to create new bean while using the #Configuration an #Bean this way:
package com.spring.beans.ParkingCar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarMaker
{
#Bean
public CarBean createNewCar()
{
CarBean carBean=new CarBean();
return carBean;
}
}
package com.spring.beans.ParkingCar;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarBean
{
private int x = 3;
static Logger logger = Logger.getLogger(CarBean.class);
public void driveCar()
{
logger.debug("I am driving my car" + x);
}
}
and then my test class looks like this:
public static void execute()
{
try
{
PropertyConfigurator.configure("log4j.properties");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CarMaker carMaker = (CarMaker) context.getBean("carMaker");
CarBean carBean = carMaker.createNewCar();
carBean.driveCar();
}
catch (Throwable e)
{
logger.error(e);
}
}
my applicationContext.xml looks like this:
<?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"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan
base-package="com.spring.beans.ParkingCar">
</context:component-scan>
<aop:aspectj-autoproxy />
<bean id="Spring3HelloWorldBean" class="com.spring.aspect.Spring3HelloWorld">
<property name="myname" value="idan" />
</bean>
<bean id="SecurityAspect" class="com.spring.aspect.SecurityAspect">
</bean>
<bean id="CalculateStrategyBean" class="com.spring.beans.calculator.CalculateStrategyBean">
<constructor-arg value="plus" />
</bean>
<bean id="CalculatorBean" class="com.spring.beans.calculator.CalculatorBean">
<constructor-arg ref="CalculateStrategyBean" />
<constructor-arg ref="CalculateNumbersHolderBean" />
</bean>
<bean id="CalculateNumbersHolderBean" class="com.spring.beans.calculator.CalculateNumbersHolderBean">
<constructor-arg value="10" />
<constructor-arg value="20" />
</bean>
<bean id="lisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="333" p:isValidateCar="true" />
<bean id="AmbulancelisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="999" p:isValidateCar="false" />
<bean id="TransitlisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="111" p:isValidateCar="false" />
<bean id="TransitVechileDetails" class="com.spring.beans.ParkingCar.VechileDetails"
p:modelName="Transit-AS" p:numOfWheels="4" p:year="1992" />
<!-- Wiring without annotations-->
<!--
<bean id="Ambulance"
class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997"
p:lisenceDrive-ref="AmbulancelisenceDrive" /> <bean id="Bike"
class="com.spring.beans.ParkingCar.TwoWheelsVechile" autowire="byName"
p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" /> <bean
id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive" autowire="constructor">
-->
<bean id="Ambulance" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997" p:lisenceDrive-ref="AmbulancelisenceDrive" />
<!-- Wiring with annotations
<bean id="Bike" class="com.spring.beans.ParkingCar.TwoWheelsVechile"
autowire="byName" p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" />
<bean id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive">
</bean>
-->
</beans>
Now when I ran it on MyEclipse thru main it worked just fine. but when I uploaded it to my stand alone application which is running on Linux I got:
2012-07-01 14:11:21,152 com.spring.test.Spring3HelloWorldTest [ERROR] org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'carMaker' is defined
Any idea why it didn't work there?
Thanks.
#Configuration indicates that a class declares one or more #Bean methods while #Bean creates a new bean which have same name as the name of the method annotated with #Bean .
In your code sample bean with name createNewCar will be created as method createNewCar() method is annotated by #Bean.
Try this
CarBean carBean = (CarBean) context.getBean("createNewCar");
carBean.driveCar();
Few things to look at
Why to annotate class CarBean as #Configuration? It dont contain any bean defination ie. method with #Bean annotation.
Why to invoke createNewCar() method as it is already annotated with #Bean? (Let Spring do its work)
Check this link it will help you to get familiar with #Configuration and #Bean annotation.

Categories