Im trying to start Tomcat but when I try start it im getting the following error
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countriesDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.fexco.helloworld.web.util.CustomHibernateDaoSupport.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
CountriesDao
package com.fexco.helloworld.web.dao;
import com.fexco.helloworld.web.model.Countries;
public interface CountriesDao {
void save(Countries countries);
void update(Countries countries);
void delete(Countries countries);
Countries findByCountry(String country);
}
The start of CountriesDaoImpl
package com.fexco.helloworld.web.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.fexco.helloworld.web.model.Countries;
import com.fexco.helloworld.web.util.CustomHibernateDaoSupport;
#Repository("countriesDao")
public class CountriesDaoImpl extends CustomHibernateDaoSupport implements CountriesDao{
public void save(Countries countries){
getHibernateTemplate().save(countries);
}
......
}
Some of Application-config.xml
<bean id="countriesDao" class="com.fexco.helloworld.web.dao.CountriesDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
....
<context:annotation-config />
<context:component-scan base-package="com.fexco.helloworld.web" />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
CustomHibernateDaoSupport class
package com.fexco.helloworld.web.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{
#Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
}
Is the error because CountriesDaoImpl isnt really implementing CountriesDao?
Does anyone know how to solve this error?
Thanks
It seems you do not have session factory defined in your dao Implementation class. You should defined one if not already defined And avoid using both configurations It will messed up things i.e
#Autowired
#Qualifier("sessionFactory")
public void seSessionFactory(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
Related
I am using #ComponentScan on SpringBootApplication to run cron, below is my code
package com.ravi
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
#org.springframework.boot.autoconfigure.SpringBootApplication
#ComponentScan(basePackages= {"com.ravi","com.ravi.cron"})
#EnableScheduling
public class SpringBootApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringBootApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
Cron :
package com.ravi.cron
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
#Lazy(false)
public class CleanDataJob {
private static Logger logger = Logger.getLogger(CleanDataJob.class);
#Autowired
DeleteDataFromDatabase deleteData;
#Scheduled
public void deleteData() {
// Cleaning data job code
deleteData.cleanData();
}
}
Below class is Autowired in cron
com.ravi.logic
import org.springframework.stereotype.Service;
#Service
public class DeleteDataFromDatabase {
public void cleanData() {
// Clean data code
}
}
If want to delete #ComponentScan annotation from SpringBootApplication, but below error is showing
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/com.ravi]]
And second error is
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cleanDataJob ': Unsatisfied dependency expressed through field 'deleteData'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ravi.logic.DeleteDataFromDatabase' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
After deleting #ComponentScan getting a 404 error on the web
On DeleteDataFromDatabase, checked with #Configuration, #Controller but not resolved
I am getting
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'springTest': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.learn.stackoverflow.general.Person
com.learn.stackoverflow.general.SpringTest.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.learn.stackoverflow.general.Person] 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)}
even after using all the annotations, I have annotated all my classes with #Component and adding component scan but still #Autowired gives me error.
Below are my classes:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
#Component
public class SpringTest {
#Autowired
Person person;
public static void main(String[] args) {
testApplicationContext();
}
private static void testApplicationContext() {
// here static and instance initializers of Person class will be invoked right away, even when we are not calling getBean method
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("C:\\E_Drive\\Projects\\Workspace\\Test\\CS101\\src\\com\\learn\\stackoverflow\\general\\bean.xml");
SpringTest springTest = (SpringTest) applicationContext.getBean("springTest");
}
}
Person class:
import org.springframework.context.annotation.Scope;
import com.bea.core.repackaged.springframework.stereotype.Component;
#Component
#Scope(value="singleton")
public class Person {
static{
System.out.println("1");
}
{
System.out.println("2");
}
}
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: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:component-scan base-package="com.learn.stackoverflow.general"/>
<!-- <bean id = "person" class = "com.learn.stackoverflow.general.Person" scope="singleton">
</bean> -->
<bean id = "springTest" class = "com.learn.stackoverflow.general.SpringTest" scope="singleton">
</bean>
</beans>
Use the right import in the Person.class. Instead of
import com.bea.core.repackaged.springframework.stereotype.Component;
you have to use
import org.springframework.stereotype.Component;
BTW you can avoid using
#Scope(value="singleton")
since singleton is a default scope for Spring beans.
I want to ask, whats wrong with this error?
I already check with other entity, they're doing good. But, can you guys help me for this trouble? Thankyouu
Error creating bean with name 'masterVersionServiceImpl' defined in file
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'masterVersionRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type MasterVersion!
Here my code
import java.sql.Connection;
import java.sql.DriverManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
#Service
public class MasterVersionServiceImpl extends CrudServiceImpl<MasterVersion, Long> implements MasterVersionService{
#Autowired
private PasswordEncoder passwordEncoder;
private MasterVersionRepository masterVersionRepo;
#Autowired
public MasterVersionServiceImpl(MasterVersionRepository jpaRepository) {
super(jpaRepository);
this.masterVersionRepo = jpaRepository;
}
public void setMasterVersionRepo(MasterVersionRepository masterVersionRepo) {
this.masterVersionRepo = masterVersionRepo;
}
//and other function
//the repository interface
import org.springframework.stereotype.Repository;
#Repository
public interface MasterVersionRepository extends BaseRepository<MasterVersion, Long>{
MasterVersion findById(Long id);
MasterVersion findByName(String name);
}
I'm using constructor-based dependency injection to inject a javax.inject.Provider<T> to a service. With Spring Framework (4.2.5), NoSuchBeanDefinitionException will be thrown saying "No qualifying bean of type [T] found for dependency. Why is T expected by Spring while injecting javax.inject.Provider<T>?
Here's the sample code:
Provider:
import javax.inject.Provider;
public class MessageProvider implements Provider<String> {
#Override
public String get() {
return "Hello!";
}
}
Service:
import javax.inject.Inject;
import javax.inject.Provider;
public class GreetingService {
private final String message;
#Inject
GreetingService(Provider<String> provider) {
// GreetingService(MessageProvider provider) { // this works!
this.message = provider.get();
}
public String greeting() {
return message;
}
}
Test:
import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class GreetingServiceTest {
#Test
public void testSomeMethod() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(MessageProvider.class);
ctx.register(GreetingService.class);
ctx.refresh();
GreetingService bean = ctx.getBean(GreetingService.class);
String message = bean.greeting();
assertNotNull(message);
}
}
And here's the error message:
Error creating bean with name 'greetingService': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [GreetingService]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
You're question is a bit ambiguous. Are you asking why Spring needs a bean that can create a T or are you asking why Spring isn't injecting an instance of your MessageProvider class?
If your question is the former then the problem you are facing is that Provider<T> is an interface, not a class. When you inject Provider<String> Spring says, "Hmm, I don't see any bean definition for the Provider interface, is there another way I can satisfy this dependency?" And Spring's answer is, "Yes, I can create an instance of org.springframework.beans.support.DefaultListableBeanFactory$DependencyProvider, but only if I know how to create T, i.e. there is a bean definition for T."
Your sample code should work if you added a configuration class to define a bean of type String:
#Configuration
public class MyConfiguration
{
#Bean
public String getMessage()
{
return "Hello!";
}
}
But if you are asking why Spring isn't injecting an instance of your MessageProvider class I suspect the problem is that it's not properly defined. You could add a qualifier to the MessageProvider definition and usage
#Component("MyMessageProvider")
public class MessageProvider implements Provider<String> {
...
and
#Inject
GreetingService(#Qualifier("MyMessageProvider") Provider<String> provider) {
...
to say exactly which Provider implementation you want injected.
I created an interface and a class:
public interface UserService {
List<User> listAll();
}
#Transactional
public class DefaultUserService implements UserService {
private String tableName;
public List<User> listAll() { someDao.listAllFromTable(tableName); }
public void setTableName(String tableName) { this.tableName = tableName; }
}
Also in my application context xml file context.xml, I defined:
<bean id="userService" class="mypackage.DefaultUserService">
<property name="tableName" value="myusers" />
</bean>
Then I want to test the DefaultUserService:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:context-test.xml"})
#TransactionConfiguration(transactionManager = "testTransactionManager")
#Transactional
public class UserServiceTest {
#Autowired
private DefaultUserService userService;
#Before
public void setup() {
userService.setTableName("mytesttable");
}
#Test
public void test() {
// test with userService;
userService.listAll();
}
}
Notice it uses context-test.xml, which imported the original context.xml:
<import resource="classpath:context.xml"/>
Unfortunately, when the test starts, spring throws exception:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mypackage.UserServiceTest':
Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private mypackage.DefaultUserService mypackage.userService
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [mypackage.DefaultUserService] 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)}
I'm not sure where is wrong, why spring can't find the bean DefaultUserService I defined?
It's because #Transactional places the bean is behind a jdk proxy implementing UserService interface, after that the bean is only available as UserService and not DefaultUserService.
See https://stackoverflow.com/a/18875681/241986.
You can try setting the table name with a property placeholder #Value("${someprop}") and define that property in test context, or create another interface that will expose setTableName(), and autowire that helper interface into the test case.
I'm not sure there are any easy solutions of the problem, I think this task can be subsumed under the problem of bean redefinition in Spring test-context framework
Spring beans redefinition in unit test environment
Try to replace the class DefaultUserService to the interface UserService
public class UserServiceTest {
#Autowired
private UserService userService;
....
}
You have not defined the getter for your property tableName in your implementing class.Spring IOC container works on the POJO model