So I am trying to use a bean generated in another class to be used in the main application
package com.simon.spring.basics.properties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class SomeExternalService {
#Value("${external.service.url}")
private String url;
public String returnServiceURL(){
return url;
}
}
And the main application is here:
package com.simon.spring.basics.springin5steps;
import com.simon.spring.basics.properties.SomeExternalService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#SpringBootApplication
//#PropertySource("classpath:application.properties")
#ComponentScan()
public class SpringIn5StepsPropertiesApplication {
public static void main(String[] args) {
ApplicationContext applicationContext =
SpringApplication.run(SpringIn5StepsPropertiesApplication.class, args);
SomeExternalService service = applicationContext.getBean(SomeExternalService.class);
System.out.println(service);
}
}
So basically a Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.simon.spring.basics.properties.SomeExternalService' available is being thrown.
What Can I do to fix this error and to avoid the same problems later on
Put SpringIn5StepsPropertiesApplication in your package root;
package com.simon.spring.basics
also remove unnecessary #ComponentScan()
#SpringBootApplication will automatically trigger a component scan under all packages from the location of main class, namely com.simon.spring.basics, so your component in com.simon.spring.basics.properties can be picked up.
Otherwise it will try to find beans under com.simon.spring.basics.springin5steps and fail to find SomeExternalService
If moving the main class is not an option, then you can add the other package like;
#SpringBootApplication(scanBasePackageClasses = {com.simon.spring.basics.properties.SomeExternalService.class})
Related
This is my project package structure.
org.myApp
MainApplication.java
org.myApp.controller
org.myApp.repositories
org.myApp.utils
I have a #SpringBootApplication placed in my org.myApp.MainApplication class and I'm expecting that it will scan all my subpackages for components as they are placed in the same package as this main class.
However, I have created this new class in org.myApp.utils called Utils which is not being picked up by the application context.
package org.myApp.utils;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
#Configuration
public class Utils {
Utils() throws IOException{
getAllProps();
}
#Bean
public static Properties getAllProps() throws IOException{
return new Properties();
}
}
The class is only scanned when I explicitly use a #ComponentScan("org.myApp.Utils") in my MainApplication.java class however this breaks the rest of my application for some reason.
How do I ensure that my Utils class is scanned and placed in the application context?
I'm facing an error that mentioned below, related to Spring Aspect Oriented Programming.
2022-05-06 17:26:44 ERROR org.springframework.boot.SpringApplication.java Line 826: Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'projectingArgumentResolverBeanPostProcessor' defined in class path resource [org/springframework/data/web/config/ProjectingArgumentResolverRegistrar.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut
Previously I used applicationContext.xml file. But after I added #Configuration annotation to the CommonController class and removed applicationContext.xml file. I just search some solutions and apply to my code, but still didn't clear my issue. Hope your support and attach my code below, thank you.
Aspect.java
package com.intervest.medical.aggregator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Aspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void aspect() {
logger.info("FFFFFFFFFFFFF {} | request {} | registerParam {}", "RETURNVALUE", "request", "registerParam");
}
}
CommonController.java
package com.intervest.medical.aggregator.controller;
import com.healix.blackboxdirect.ArrayOfString;
import com.healix.blackboxdirect.DirectServiceSoap;
import com.intervest.medical.engine.domain.*;
import com.intervest.medical.engine.service.*;
import com.intervest.medical.engine.util.*;
import com.intervest.medical.engine.constants.RegisterError;
import com.intervest.medical.engine.constants.RegisterState;
import com.intervest.medical.engine.dto.ValidationDTO;
import com.intervest.medical.engine.dto.XmlResultDTO;
import com.intervest.medical.engine.enums.Stub;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
#Controller
#Aspect
#Configuration
public class CommonController {
private static final Logger LOG = LoggerFactory.getLogger(CommonController.class);
#Autowired
ScreeningProxyService screeningProxyService;
#Autowired
MedicalDataKeeperService medicalDataKeeperService;
#Autowired
private MedicalUrlService medicalUrlService;
#Autowired
private MedicalConstantsService medicalConstantsService;
#Autowired
private MedicalConfigService medicalConfigService;
#ResponseBody
#Pointcut("within(com.intervest.medical.aggregator.Aspect.*)")
#Before("reScreenAndGetXmls(#RequestBody RegisterParam registerParam)")
#RequestMapping(value = "/medical/screeningData/register", method = RequestMethod.POST)
public RegisterResult doScreen(HttpServletRequest request, #RequestBody RegisterParam registerParam) {
ValidationDTO intiValidationDTO = screeningProxyService.initialValidation(registerParam, false);
if (!intiValidationDTO.isSuccess()) {
return new RegisterResult(null, intiValidationDTO.getErrMsg());
}
........................
}
Application.java
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.setBannerMode(Banner.Mode.OFF);
Environment environment = springApplication.run(args).getEnvironment();
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
Aspect e = (Aspect) applicationContext.getBean("Aspect");
e.aspect();
}
I solved my issue. There was an issue with my Aspect class. I didn't add relevant annotations to that class. I was able to solve the issue after adding those annotations to the Aspect class and removing unwanted annotations from controller class.
package com.intervest.medical.aggregator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#org.aspectj.lang.annotation.Aspect
#Component
public class Aspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void aspect() {
logger.info("FFFFFFFFFFFFF {} | request {} | registerParam {}", "RETURNVALUE", "request", "registerParam");
}
}
This is the error which i am getting:
Description:
Field andiRepository in com.service.datafetcher.AllAndisDataFetcher required a bean of type 'com.repositories.AndiRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.repositories.AndiRepository' in your configuration.
This is the data fetcher file which is requiring a bean:
import com.models.Andi;
import com.repositories.AndiRepository;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public class AllAndisDataFetcher implements DataFetcher<List<Andi>> {
#Autowired
AndiRepository andiRepository;
#Override
public List<Andi> get(DataFetchingEnvironment dataFetchingEnvironment) throws Exception {
return andiRepository.findAll();
}
}
this is the main method which resides in "com".
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan("com.repositories")//to scan repository files
#EntityScan("com.models")
#EnableJpaRepositories("com.repositories.AndiRepository")
public class DynamoDBApplication {
public static void main(String[] args) {
SpringApplication.run(DynamoDBApplication.class, args);
}
}
The models, repositories, service, packages are inside the main com package.
This is the repository file:
package com.repositories;
import com.andiskillsmaxmodels.Andi;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AndiRepository extends CrudRepository<Andi, Integer> {
}
Thank you
Correct your package names. They're all over the place. You have imported classes from different packages it seems. Make sure that AndiRepository is in the com.repositories package. And Andi class in your com.models package. After correcting these mistakes do the following.
Remove #ComponentScan("com.repositories"). You don't need this, since #SpringBootApplicationautomatically does it for you.
And replace #SpringBootApplication with #SpringBootApplication(scanBasePackages = "com")
I'm working on Spring over Hibernate project an i'm only in the beginning.
I'm tryng to hav a SpringBootApplication which writes to MsSql some LogEntries objects.
I have some different packages:
here is the classes:
LogEntryFacadeImpl.class :
package com.tradingSystem.dataAccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tradingSystem.entity.LogEntry;
#Service
public class LogEntryFacadeImpl implements LogEntryFacade{
#Autowired
private LogEntryDAO logEntryDao;
#Transactional
#Override
public Long addLogEntry(LogEntry log) {
return this.logEntryDao.save(log).getId();
}
#Override
public LogEntry getLogEntry(Long logId) {
return this.logEntryDao.findOne(logId);
}
}
LogEntryDAO.class:
package com.tradingSystem.dataAccess;
import org.springframework.data.jpa.repository.JpaRepository;
import com.tradingSystem.entity.LogEntry;
public interface LogEntryDAO extends JpaRepository<LogEntry, Long> {
}
and I use this class as tester:
TestApplication.class:
package com.testings;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.tradingSystem.dataAccess.LogEntryFacade;
import com.tradingSystem.entity.LogEntry;
#SpringBootApplication
#ComponentScan({"com.tradingSystem" })
public class TestApplication implements CommandLineRunner{
#Autowired
private LogEntryFacade logEntryFacade;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
LogEntry log = new LogEntry(552266, "Testing of log entry save",
new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis()));
System.err.println(log);
Long id = logEntryFacade.addLogEntry(log);
LogEntry log2 = logEntryFacade.getLogEntry(id);
System.err.println(log2);
}
}
wher i run this as application i get this message in console:
APPLICATION FAILED TO START
Description:
Field logEntryDao in com.tradingSystem.dataAccess.LogEntryFacadeImpl required a bean of type 'com.tradingSystem.dataAccess.LogEntryDAO' that could not be found.
Action:
Consider defining a bean of type 'com.tradingSystem.dataAccess.LogEntryDAO' in your configuration.
I put the #ComponentScan({"com.tradingSystem" }) annotation in the tester as you can see. however, still get this message.
(when I didnt use any packages separation, everything works fine...)
Please help me solve this
Thanks
You should add #Repository annotation above your Repository interface.
Optionally you can add it like #Repository(value="logEntryRepository")
the default scan path is package of #SpringBootApplication class, so you must declare three scan path, but it's seems like that you missing two scan config, you need add
#EnableJpaRepositories(basePackages = "com.tradingSystem.dataAccess")
#EntityScan(basePackages = "com.tradingSystem.entity")
#ComponentScan(basePackages = "com.tradingSystem.dataAccess")
to the TestApplication class
I've seen a lot of questions about this error before, but no resolution that works for me.
I'm new to Spring, but trying to use the Spring Data for Neo4J library for a project. I decided to start with a quick spike to make sure I know how everything is working, and so I set up a simple App class with a main method like so:
package org.example.neo4jSpike;
import org.example.neo4jSpike.domain.Actor;
import org.example.neo4jSpike.repositories.ActorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
/**
* Hello world!
*
*/
#Component
public class App
{
#Autowired
private ActorRepository actors;
#SuppressWarnings("resource")
public static void main( String[] args )
{
ApplicationContext context = new AnnotationConfigApplicationContext(SpikeConfiguration.class);
App a = context.getBean(App.class);
a.init();
}
private void init(){
Actor michaelDouglas = actors.save(new Actor("Michael Douglas"));
System.out.println( "Hello World!" );
System.out.println(michaelDouglas.getId());
System.out.println("Total people: " + actors.count());
}
}
I have the configuration class setup as well:
package org.example.neo4jSpike;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableNeo4jRepositories(basePackages = "org.example.neo4jSpike.repositories")
#EnableTransactionManagement
public class SpikeConfiguration extends Neo4jConfiguration{
#Bean
public SessionFactory getSessionFactory() {
// with domain entity base package(s)
return new SessionFactory("org.example.neo4jSpike.domain");
}
// needed for session in view in web-applications
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
I'll add the code for my repositories and domain classes if needed, but they're all set up in a similar manner, and are all pretty simple.
When I try and run the main, however, I get
No qualifying bean of type [org.example.neo4jSpike.App] is defined
I don't see how it's not defined, it's right there, defined as an #Component. What am I misunderstanding?
Doesn't matter if you put the #Component annotation if Spring is not scanning your class package. You can add a #ComponentScan annotation in you configuration class and configure it to scan the package where your App class is located. Alternatively you can remove the #Component annotation and declare a Bean of type App in the configuration class.
Hope this can help.