public class PartnershipMaintenanceFunction
{
final Logger logger = LoggerFactory.getLogger( PartnershipMaintenanceFunction.class );
#Autowired
PartnershipMaintenanceController partnershipMaintenanceServiceController;
public RetrievePartnershipResponse retrievePartnership( Message<RetrievePartnershipRequest> messageRequest )
{
RetrievePartnershipRequest retrievePartnershipRequest = messageRequest.getPayload();
MessageHeaders header = messageRequest.getHeaders();
return partnershipMaintenanceServiceController.retrievePartnership( retrievePartnershipRequest );
}
}
controller class
#RestController
#Api( "Partnership Maintainence" )
public class PartnershipMaintenanceController
{
final Logger logger = LoggerFactory.getLogger( PartnershipMaintenanceController.class );
#Autowired
PartnershipService partnershipService;
public void setPartnershipService( PartnershipService partnershipService )
{
this.partnershipService = partnershipService;
}
#GET
#Path( "/retrievePartnershipRequest" )
#ApiOperation( "Retrieve Partnership" )
public RetrievePartnershipResponse retrievePartnership( RetrievePartnershipRequest request )
{
return partnershipService.retrievePartnership( request );
}
}
public class PartnershipMaintenanceFunction
{
final Logger logger = LoggerFactory.getLogger( PartnershipMaintenanceFunction.class );
#Autowired
PartnershipMaintenanceController partnershipMaintenanceServiceController;
}
controller class
#RestController
#Api( "Partnership Maintainence" )
public class PartnershipMaintenanceController
{
final Logger logger = LoggerFactory.getLogger( PartnershipMaintenanceController.class );
#Autowired
PartnershipService partnershipService;
public void setPartnershipService( PartnershipService partnershipService )
{
this.partnershipService = partnershipService;
}
Error creating bean with name 'partnershipMaintenanceController':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field:
com.cgi.bkifs.bso.prime.partnership.maintainence.service.PartnershipService
com.cgi.bkifs.rest.service.controller.PartnershipMaintenanceController.partnershipService;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.cgi.bkifs.bso.prime.partnership.maintainence.service.PartnershipService]
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)}
Probably you forgot to making PartnershipService as Spring Bean.
#Component
public class PartnershipService{}
If the bean ( PartnershipService ) is Normal bean then you can use #Component
If the bean (PartnershipService ) is service bean ( Service layer ) then you can use #service
Information about #Component, #Service, #Controller, and #Repository
annotation do in Spring Framework: #Component is a generic stereotype
for any Spring-managed component or bean. #Repository is a stereotype
for the persistence layer. #Service is a stereotype for the service
layer. #Controller is a stereotype for the presentation layer
(spring-MVC).
The error messages says:
Could not autowire field:
com.cgi.bkifs.bso.prime.partnership.maintainence.service.PartnershipService
Assuming that you already declared a class PartnershipService and it has the #Service annotation it is likely that you did not define the component scan.
Either add
#ComponentScan(basePackages = "com.cgi.bkifs.bso.prime.partnership") or in older versions use the xml file to define the scope of component scan:
<?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.cgi.bkifs.bso.prime.partnership"/>
</beans>
Related
I've created this class:
public class ActivitiWorkflowService {
private final TaskService taskService;
..
}
but I have this problem when init the project:
No qualifying bean of
type 'org.activiti.engine.TaskService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I expect that your class has a constructor such as:
public class ActivitiWorkflowService {
private final TaskService taskService;
public ActivitiWorkflowService(TaskService taskService) {
this.taskService = taskService;
}
}
The error you are getting is because Spring cannot autowire this class to the ActivitiWorkflowService - it probably was not defined in the Spring context.
Depending on the configuration you use you can either:
Define class with #Component or #Service annotation and let #ComponentScan do its work:
#Component //#Service
public TaskService {
...
}
or if you are using #Configuration class define the bean of type TaskService
#Configuration
public class AppConfig {
#Bean
public TaskService taskService() {
return new TaskService();
}
#Bean
public ActivitiWorkflowService activitiWorkflowService(TaskService taskService) {
return new ActivitiWorkflowService(taskService);
}
}
I am writing the integration tests with #WebFluxTest for my #RestController.
Here are my classes:
#RestController
#RequestMapping("/usager")
public class UsagerController {
#Autowired
private UsagerService usagerService;
#GetMapping
public Usager getUsager() {
return usagerService.create();
}
}
#Service
public class UsagerService implements CrudService<Usager, Integer> {
#Autowired
private UsagerRepository usagerRepository;
#Override
public JpaRepository<Usager, Integer> getRepository() {
return usagerRepository;
}
#Override
public Usager create() {
return new Usager();
}
}
#Repository
public interface UsagerRepository extends JpaRepository<Usager, Integer>, JpaSpecificationExecutor<Usager> {
}
#ExtendWith(SpringExtension.class)
#WebFluxTest(UsagerController.class)
#Import({ UsagerService.class, UsagerRepository.class })
#Tag(TestCase.INTEGRATION)
public class UsagerControllerIT {
#Autowired
private WebTestClient wtc;
#Test
public void getUsager_returnUsager() {
ResponseSpec rs = wtc.get().uri("/usager").exchange();
rs.expectStatus().isOk();
rs.expectHeader().contentType(MediaType.APPLICATION_JSON);
rs.expectBody(Usager.class).isEqualTo(new Usager());
}
}
I get the following exception:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dsi.bibliosys.biblioback.repository.UsagerRepository]: Specified class is an interface
I don't understand why Spring can't inject the repository.
Does somebody have an idea ?
I tried another approach using #SpringBootTest. Here is my new test class :
#ExtendWith(SpringExtension.class)
#SpringBootTest
#Tag(TestCase.INTEGRATION)
public class UsagerController02IT {
#Autowired
private UsagerController usagerController;
#Test
public void getUsager_returnUsager() {
WebTestClient wtc = WebTestClient.bindToController(usagerController).build();
ResponseSpec rs = wtc.get().uri("/usager").exchange();
rs.expectStatus().isOk();
rs.expectHeader().contentType(MediaType.APPLICATION_JSON);
rs.expectBody(Usager.class).isEqualTo(new Usager());
}
}
I get this exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.dsi.bibliosys.biblioback.controller.UsagerController': Unsatisfied dependency expressed through field 'usagerService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.dsi.bibliosys.biblioback.service.entity.UsagerService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I don't understand why UserService is not available in the application context.
Thanks for your help.
This looks very similar to this. I'd suggest investigating your test configuration and adding it if appropriate.
A quote from Spring on #WebFluxTest
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to WebFlux tests (i.e. #Controller, #ControllerAdvice, #JsonComponent, Converter/GenericConverter, and WebFluxConfigurer beans but not #Component, #Service or #Repository beans).
I'm trying to implement Spring AOP in multiple layers application and make advice for #Service and #Controller classes.
Everything works fine without aspect class. When I add that part of code it causes Spring configuration problem.
#Aspect class:
#Aspect
#Component
public class ApplicationMonitor {
private static final Logger logger = Logger.getLogger(ApplicationMonitor.class);
#Pointcut(value = "execution(* hr.mycompany.controller.impl.MyCompanyController.update(*)) && args(obj)")
public void updateMC(Object obj){}
#Before(value="updateMC(obj)")
public void beforeUpdateMC(JoinPoint jp, Object obj) {
Object obj = jp.getArgs()[0];
logger.info("beforeUpdateMC " + obj);
}
}
Spring XML aspect configuration:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Application #Controller and #Service classes:
#Controller
public class MyCompanyController implements IMyCompanyController{
#Autowired
private IMyComapnyService myCompanyService;
}
#Service
public class MyCompanyService implements IMyComapnyService {
#Autowired
private IGenericHibernateDao<Object, Integer> vwObjectDao;
}
Error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hr.mycompany.dao.IGenericHibernateDao] 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)}
09:11:27,871 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/BasicData-portlet]] (http--0.0.0.0-8083-2) StandardWrapper.Throwable: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyCompanyService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private hr.mycompany.dao.IGenericHibernateDao hr.mycompany.services.impl.MyCompanyService.vwObjectDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hr.mycompany.dao.IGenericHibernateDao] 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)}
Where the problem is?
EDIT:
Part of class with Hibernate methods:
#Transactional(readOnly = true)
public abstract class GenericHibernateDao<T, PK extends Serializable> implements IGenericHibernateDao<T, PK> {
private static final Logger log = LoggerFactory.getLogger(GenericHibernateDao.class);
#Autowired
#Qualifier(value = "hibernateSessionFactory")
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = false)
public PK save(T entity) {
Assert.notNull(entity, "Argument entity cannot be null in a call to GenericHibernateDao.save !");
Session session = getSessionFactory().getCurrentSession();
return (PK) session.save(entity);
}
...
}
EDIT (22-02-2019):
When I change this line of code:
<aop:aspectj-autoproxy proxy-target-class="true"/>
like this:
<aop:aspectj-autoproxy />
Error disapears, but aspect does not work.
I found solution.
I change this line of code in Spring XML config file:
<aop:aspectj-autoproxy proxy-target-class="true"/>
I set proxy-target-class to false:
<aop:aspectj-autoproxy proxy-target-class="false"/>
I deleted this dependency from pom.xml file:
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
I set the same spring-aop vesion like Spring version I use in Spring XML config file.
I changed this:
http://www.springframework.org/schema/aop/spring-aop.xsd
like this:
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
I am using a mock repository for my application.
Here is snippet how service looks:
#Service
public class WeatherStationService {
#Autowired
private WeatherStationRepositoryMock weatherRepository;
Here is repository code:
#Repository
public class WeatherStationRepositoryMock {
#Getter
private List<WeatherStation> stations = new ArrayList<>(
Arrays.asList(
new WeatherStation("huston", "Huston station", RandomGenerator.getRandomGeoInformation()),
new WeatherStation("colorado", "Colorado station", RandomGenerator.getRandomGeoInformation())
)
);
It works fine when I am executing main() with #SpringBootApplication.
However, when I want to run test class:
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = MockConfig.class)
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class WeatherStationServiceTest {
#Autowired
#Real
private WeatherStationService weatherService;
It fails with the following stacktrace:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.lelyak.repository.WeatherStationRepositoryMock' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Here is MockConfig content:
#Configuration
public class MockConfig {
//**************************** REAL BEANS ******************************
#Bean
#Real
public WeatherStationService weatherServiceReal() {
return new WeatherStationService();
}
Real is marker annotation for real instances:
#Retention(RUNTIME)
#Qualifier
public #interface Real {
}
I can fix it with next initialization at service:
#Service
public class WeatherStationService {
private WeatherStationRepositoryMock weatherRepository = new WeatherStationRepositoryMock();
It works fine.
Why does this happen?
How to fix autowiring for my custom repository class?
#SpringBootApplication implicitly defines #ComponentScan, which scans all subpackages for beans.
When you run a test using MockConfig's, it doesn't scan for beans.
Solution - use #ComponentScan OR define beans in MockConfig
(1) Using #ComponentScan:
#Configuration
#ComponentScan //Make sure MockConfig is below all beans to discover
public class MockConfig {
#Bean
#Real
public WeatherStationService weatherServiceReal() {
return new WeatherStationService();
}
}
(2) or define required beans:
#Configuration
public class MockConfig {
#Bean
#Real
public WeatherStationService weatherServiceReal() {
return new WeatherStationService();
}
#Bean
public WeatherStationRepositoryMock weatherStationRepository() {
return new WeatherStationRepositoryMock()
}
}
I'm trying to autowire an interface inside a controller bean
In my context configuration file I've put
<context:annotation-config />
and
<bean id="viewVerbale" class="com.sirfe.controller.VerbaliController" />
my controller class is
#Controller
public class VerbaliController {
#Autowired
VerbaliRepository repository;
private static final Logger logger = LoggerFactory.getLogger(VerbaliController.class);
#RequestMapping(value = "/sirfe/verbale/{sequVerbale:.+}", method = RequestMethod.GET)
public ModelAndView viewVerbale(#PathVariable("sequVerbale") String sequVerbale) {
logger.debug("welcome() - sequVerbale {}", sequVerbale);
Verbali verbale = repository.findOne(Long.parseLong(sequVerbale));
ModelAndView model = new ModelAndView();
model.setViewName("sirfe/verbali/viewVerbale");
model.addObject("sequVerbale", sequVerbale);
return model;
}
}
my interface signature is
public interface VerbaliRepository extends CrudRepository<Verbali, Long> { }
and when I launch my app I get
Could not autowire field: com.sirfe.repository.VerbaliRepository com.sirfe.controller.VerbaliController.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sirfe.repository.VerbaliRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Looks like you're trying to use Spring JPA repository.
In order to have Spring create bean for your repository interfaces, you need in applicationContext.xml to declare what package to scan
<jpa:repositories base-package="com.sirfe.repository" />
Doing so, Spring will generate bean implementing the interface for you.
See Spring JPA Repositories
Spring is complaining that it cannot find a valid bean definition that matches, ie there is no bean defined that is an implementation of VerbaliRepository.
You need to define a bean or alternatively annotate an implementation class with #Component eg
<bean id="myRepository" class="com.foo.bar.MyRepository" />
or
#Component
public class MyRepository implements VerbaliRepository {
....
}