spring boot,No qualifying bean of type found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency - spring-boot

#Controller
#EnableAutoConfiguration
public class ControllerShowInfo
{
#RequestMapping("/")
public String rawPage()
{
return "rawPage";
}
#Autowired
stockreviewsRepositoryDao repository;
#RequestMapping("/getBaseInfo")
#ResponseBody
public JSONArray getReviewsInfo()
{
JSONArray jsonArray = new JSONArray();
for (stockreviewsBean reviewBean : repository.findAll())
{
jsonArray.put(reviewBean);
System.out.println(reviewBean.getTitle());
}
return jsonArray;
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(ControllerShowInfo.class, args);
}
}
this is controller layer.
public interface stockreviewsRepositoryDao extends CrudRepository<stockreviewsBean,String>
{
}
this is Dao layer.
when I run ControllerShowInfo.class. There is a problem as follows:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controllerShowInfo': Unsatisfied dependency expressed through field 'repository': No qualifying bean of type [com.yxzh.mapper.stockreviewsRepositoryDao] found for dependency [com.yxzh.mapper.stockreviewsRepositoryDao]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yxzh.mapper.stockreviewsRepositoryDao] found for dependency [com.yxzh.mapper.stockreviewsRepositoryDao]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
but when I run another .class
#SpringBootApplication
public class Application
{
public static void main(String[] args) throws Exception
{
SpringApplication.run(Application.class, args);
}
}
and implement CommmandLineRunner
#Component
public class DataInitialization implements CommandLineRunner{
#Autowired
stockreviewsRepositoryDao repository;
#Override
public void run(String... args) throws Exception
{
System.out.println("-------------------------------");
int count=0;
for (stockreviewsBean reviewBean : repository.findAll())
{
count++;
System.out.println(reviewBean.getTitle());
}
System.out.println(count);
}
}
It worked well. It really confused me.

Have you tried to annotate
stockreviewsRepositoryDao with #Repository
and
Application with #EnableJpaRepositories(basePackageClasses = {"stockreviewsRepositoryDao.class"})

Related

No qualifying bean of type 'mypackage.repository' available: expected at least 1 bean which qualifies as autowire candidate

I have a test class in Junit4 that needs to use NutrientListService.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
private NutrientListService nutrientService;
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}
I was getting a null nutrientService, so I tried to set up an ApplicationContext.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Autowired
NutrientListService nutrientService;
}
However, I get
Error creating bean with name 'nutrientListService': Unsatisfied dependency expressed through field 'nutrientListRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repositories.NutrientListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the service:
#Service
#Component
public class NutrientListService {
#Autowired
private NutrientListRepository repo;
}
And the repository:
#Repository
public interface NutrientListRepository extends MongoRepository<MyClass, String> {
MyClass findByID(String ID);
}
Any ideas to wire the service properly? I need to pass it for calculation as it is one of the parameters. Do I have to use an application context class or the application-context.xml (which I could not find)? What would be the least obscure way to do this? I thank you.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Bean
NutrientListService nutrientService(){
new NutrientListService()
}
}
And then call the Bean with #Autowired
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
#Autowired
NutrientListService nutrientService
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}

Spring and ServletContextListener

I read some articles and posts here about
#Autowired
ServletContext context;
Of my realization of ServletContextListener to #Controller. But I got a long exception when run it:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'trendsoftCtrl':
Unsatisfied dependency expressed through field 'context':
No qualifying bean of type [javax.servlet.ServletContext] found for dependency [javax.servlet.ServletContext]:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [javax.servlet.ServletContext] found for dependency [javax.servlet.ServletContext]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Here are my classes.
#WebListener
public class TRSCListner implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String beanFileName = context.getInitParameter("springBeans");
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load(beanFileName);
ctx.refresh();
NewsDao newsDao = ctx.getBean("newsDao", NewsDao.class);
context.setAttribute("appContext", ctx);
context.setAttribute("dao", newsDao);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext context = event.getServletContext();
GenericXmlApplicationContext ctx = (GenericXmlApplicationContext) context.getAttribute("appContext");
ctx.close();
}
}
And another
#Controller
public class TrendsoftCtrl {
#Autowired
ServletContext context;
#RequestMapping ("/welcome")
public ModelAndView helloWorld() {
NewsDao newsDao = (NewsDao) context.getAttribute("dao");
List<News> news = newsDao.getAll();
StringBuilder message = new StringBuilder();
for (News n : news) {
message.append(n.getCategory().getName() + "<br>");
message.append(n.getName() + "<br>");
message.append(n.getData() + "<br><br>");
}
return new ModelAndView("welcome", "news", message.toString());
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
}
By default, the #Autowired will perform the dependency checking to make sure the property has been wired properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable this checking feature by setting the “required” attribute of #Autowired to false.
#Autowired(required=false)
Even if Spring can’t find a matching bean, it will leave the person property unset.

NoSuchBeanDefinitionException on using Aspect

Spring boot version used: 1.2.3
We are creating CacheManager based on a property like :
#Bean
public CacheManager cacheManager() throws IOException {
String cacheImpl = env.getProperty(CacheSupport.CACHE_PROPERTY, String.class, "");
if (CacheSupport.AEROSPIKE.equalsIgnoreCase(cacheImpl)) {
return aerospikeCacheManager();
} else if (CacheSupport.REDIS.equalsIgnoreCase(cacheImpl)) {
return redisCacheManager();
} else {
return guavaCacheManager();
}
}
We have an AerospikeController like below :
#ConditionalOnProperty(name = CacheSupport.CACHE_PROPERTY, havingValue = CacheSupport.AEROSPIKE)
#Controller
public class AerospikeController {
#Autowired
private AerospikeCacheManager aerospikeCacheManager;
}
Things were working fine. Problem arises when i added below code for intercepting response times of aerospike calls:
#Component
#Aspect
public class WebServiceResponseTimeLogger {
private static final Logger LOG = LoggerFactory.getLogger(WebServiceResponseTimeLogger.class);
#Autowired
private AerospikeCacheManager cacheManager;
#PostConstruct
void init() {
LOG.info("WebServiceRequestTimeLogger initialized");
}
public WebServiceResponseTimeLogger() {
super();
}
#Pointcut("execution(* com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager.*(..))")
public void pointcuts() {
}
#Around("pointcuts()")
public void logExternalCalls(ProceedingJoinPoint pjp) throws Throwable {
long timeStartInMillisecs = System.currentTimeMillis();
pjp.proceed();
MethodSignature signature = (MethodSignature) pjp.getSignature();
LOG.info("Time Taken to execute : {} {} is {} ms", new Object[] { signature, pjp.getArgs()[0], (System.currentTimeMillis() - timeStartInMillisecs) });
}
}
I am getting below exception :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager] 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:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 18 common frames omitted
From the logs it says :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager] 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)}
Check if bean AerospikeCacheManager is created in this code correctly.
#Bean
public CacheManager cacheManager() throws IOException {
String cacheImpl = env.getProperty(CacheSupport.CACHE_PROPERTY, String.class, "");
if (CacheSupport.AEROSPIKE.equalsIgnoreCase(cacheImpl)) {
return aerospikeCacheManager();

Unable to autowire dozer Mapper in component class in spring boot

I am new to Spring Boot. I was trying to develop small application in spring boot mvc with neo4j database. Following is my Server
#Configuration
#ComponentScan({ "myproject" })
#EnableAutoConfiguration
#EnableNeo4jRepositories(basePackages = "myproject")
public class Server extends Neo4jConfiguration implements CommandLineRunner
{
public Server()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
#Bean
Mapper mapper()
{
return new DozerBeanMapper();
}
public void run(String... args) throws Exception
{
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(Server.class, args);
}
}
Following is my main class
#Configuration
#ComponentScan({ "myproject.business" })
#EnableNeo4jRepositories(basePackages = "myproject")
public class MainWithStructure extends Neo4jConfiguration implements CommandLineRunner
{
#Autowired
private MyService myService;
public MainWithStructure()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
.......
......
public static void main(String[] args) throws Exception
{
FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));
SpringApplication app = new SpringApplication(MainWithStructure.class);
app.setWebEnvironment(false);
app.run(args);
}
}
Following is my Component class
#Component
public class MyService
{
#Autowired
private Mapper mapper; //Fails to autowire org.dozer.Mapper
.....
}
Following is my Controller class
#RestController
#RequestMapping("/rest")
public class MyController
{
#Autowired
private Mapper mapper; //autowire sucess org.dozer.Mapper
}
I got following Exception when I run main class MainWithStructure
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainWithStructure': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myproject.business.MyService myproject.main.MainWithStructure.MyService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.dozer.Mapper myproject.business.MyService.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dozer.Mapper] 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)}
Following is my project structure
demo_project
src/main/java
---myproject.main
------MainWithStructure.java
------Server.java
---myproject.business
------MyService.java
---myproject.rest
------MyController.java
If I autowire org.dozer.Mapper in Controller, it sucessfuly autowired it. BUT if I autowire org.dozer.Mapper in Component class it fails to autowire.
Why it is failing to autowire org.dozer.Mapper only on Component class?
Please make me correct if I wrong. Thank you :)
Your Server is not in one of the packages that you #ComponentScan, so the Mapper is indeed not a bean. Try removing the explicit package from the #ComponentScan (since everything is in a subpackage of the main class that will pick up all the components).
You can add #SpringBootApplication in your main class which has #ComponentScan
which will scan all your sub components in project.

error with project in spring, hibernate

This the error that I'm getting:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioControlador': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blah.base.database.DAO.UsuarioDAO com.blah.base.controlador.UsuarioControlador.usuarioDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UsuarioDAO' defined in file [C:\Users\Owner\workspaceSpring.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\base\WEB-INF\classes\com\yavale\base\database\hibernetDAO\UsuarioHibernetDao.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
This is my UsuarioControlador (controller):
#Controller
#RequestMapping("/")
public class UsuarioControlador {
private UsuarioDAO usuarioDAO;
#Autowired
public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
this.usuarioDAO = usuarioDAO;
}
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Usuario> usuarios = usuarioDAO.listarUsuarios();
model.addAttribute("usuarios", usuarios);
return "index";
}
}
This is UsuarioDAO:
public interface UsuarioDAO {
void insertarUsuario(Usuario usuario);
void modificarUsuario(Usuario usuario);
List<Usuario> listarUsuarios();
Usuario buscarUsuario(String idUsuario);
void eliminarUsuario(Usuario usuario);
}
This is the class that implements UsuarioDAO:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
#Service(value="UsuarioDAO")
public class UsuarioHibernetDao extends HibernateDaoSupport implements UsuarioDAO{
#Autowired
public UsuarioHibernetDao(#Qualifier("mySessionFactory") SessionFactory
sessionFactory) {
this.setSessionFactory(sessionFactory);
}
public void insertarUsuario(Usuario usuario) {
this.getHibernateTemplate().save(usuario);
}
public void modificarUsuario(Usuario usuario) {
this.getHibernateTemplate().update(usuario);
}
public List<Usuario> listarUsuarios() {
return this.getHibernateTemplate().find("from Usuario");
}
public Usuario buscarUsuario(String idUsuario) {
return this.getHibernateTemplate().load(Usuario.class, idUsuario);
}
public void eliminarUsuario(Usuario usuario) {
this.getHibernateTemplate().delete(usuario);
}
}
This is my servlet-context.xml: https://dl.dropboxusercontent.com/u/31349296/servlet-context.xml
I'm new with spring so Im completely lost with this.
Edit: this is the complete stack trace: https://dl.dropboxusercontent.com/u/31349296/log.txt
Edit2:
You are using the wrong identifier in the Qualifier annotation. The bean id is "mySessionFactory" but you have given "sessionFactory". Also, make sure content component scan is scanning the right packages.
Update:
The other error is probably related to the import of the hibernate session. You should be using org.hibernate.Session instead of org.hibernate.classic.Session

Resources