i have a spring data mongo repository class
public interface MyRepository extends MongoRepository<FeedbackDTO, String> {
}
in the test configuration i use the EnableMongoRepositories annotation
#EnableMongoRepositories(basePackages={"com.mypackage.repository.mongodb"})
public class ServiceTestConfiguration {
when i try to test a service class that uses this repository it throws an exception
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 57 common frames omitted
The #EnableMongoRepositories annotation will trigger creation of repository beans on startup, but you still need to register a MongoDB connection and create the MongoTemplate instance that is injected into these repositories. See the Spring Data MongoDB documentation. Here is an example:
#Configuration
#PropertySource({ "classpath:mongodb-data-source.properties" })
public class MongodbDataSourceConfig extends AbstractMongoConfiguration {
#Autowired Environment env;
#Override
public String getDatabaseName(){
return env.getRequiredProperty("mongo.name");
}
#Override
#Bean
public Mongo mongo() throws Exception {
ServerAddress serverAddress = new ServerAddress(env.getRequiredProperty("mongo.host"));
List<MongoCredential> credentials = new ArrayList<>();
credentials.add(MongoCredential.createScramSha1Credential(
env.getRequiredProperty("mongo.username"),
env.getRequiredProperty("mongo.name"),
env.getRequiredProperty("mongo.password").toCharArray()
));
MongoClientOptions options = new MongoClientOptions.Builder()
.build();
return new MongoClient(serverAddress, credentials, options);
}
}
Related
I have config with some #Bean annotations and it works.
But if I change the bean to inherit from interface it isn't work. Do I need special annotations o something like?
config class snippet without imports
#Configuration
#ComponentScan("io.github.aaa4")
//#ComponentScan({ "io.github.aaa4.dao", "io.github.aaa4.entity","io.github.aaa4.Servlets"})
#EnableTransactionManagement
public class AppConfig {
#Bean
public ComboPooledDataSource myDataSource() throws PropertyVetoException {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/emp?useSSL=false");
ds.setUser("emp");
ds.setPassword("emp");
ds.setMinPoolSize(2);
ds.setMaxPoolSize(20);
ds.setMaxIdleTime(30000);
return ds;
}
#Bean
public LocalSessionFactoryBean mySessionFactory() throws PropertyVetoException {
LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
sf.setDataSource(myDataSource());
sf.setPackagesToScan("io.github");
sf.setHibernateProperties(hibernateProperties);
return sf;
}
#Bean
#Autowired
public HibernateTransactionManager myTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
public UserDao userDaoImpl() {
return new UserDaoImpl();
}
#Bean
public DBService dBServiceImpl() {
return new DBServiceImpl();
}
}
serviceImpl snippet
#Service
public class DBServiceImpl implements DBService {
//inject user DAO
#Autowired
private UserDao userDao;
#Transactional
public void addUser(MyUser user) {
userDao.createUser(user);
}
#Transactional
public List<MyUser> getUserList() {
return userDao.getusers();
}
#Transactional
public void deleteUser(int theId) {
userDao.deleteUser(theId);
}
}
main class
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
DBServiceImpl service = ctx.getBean(DBServiceImpl.class);
MyUser user = new MyUser("alice", "and her passwd");
System.out.println("this is the user:" + user);
service.addUser(user);
service.addUser(user);
service.addUser(user);
service.addUser(user);
System.out.println("User added!");
service.deleteUser(2);
System.out.println("user number id = 2 deleted");
List<MyUser> userList = service.getUserList();
for (MyUser users : userList)
System.out.println(users);
ctx.close();
}
}
stacktrace with problem
INFO: Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource[ identityToken -> 1hge1459o1fr6qmlst9469|42e99e4a, dataSourceName -> 1hge1459o1fr6qmlst9469|42e99e4a ]] of Hibernate SessionFactory for HibernateTransactionManager
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.aaa4.services.DBServiceImpl' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
at io.github.aaa4.Main.main(Main.java:30)
with annotation #EnableAspectJAutoProxy(proxyTargetClass = true) above the config class
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:223)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:702)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:527)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at io.github.aaa4.Main.main(Main.java:14)
Caused by: java.lang.NoClassDefFoundError: org/aspectj/lang/annotation/Around
at org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.<clinit>(ReflectiveAspectJAdvisorFactory.java:77)
at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.initBeanFactory(AnnotationAwareAspectJAutoProxyCreator.java:78)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.setBeanFactory(AbstractAdvisorAutoProxyCreator.java:60)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1647)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1615)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
... 10 more
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Around
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 16 more
Try to use an interface instead of an implementation
DBService service = ctx.getBean(DBService.class);
You have #Transactional annotations on your service methods. All #Transactional annotations should be scanned at startup time and the targeted methods should become transactional. To add transactional behavior Spring creates a proxy for your class. That's why you can't get your bean.
I think,you should make changes in this line DBServiceImpl service = ctx.getBean(DBServiceImpl.class); to DBService service = ctx.getBean(DBService.class);
for reference check spring doc Using the #Bean annotation Spring DOC
"What's important to keep in mind is that, if the transactional bean is implementing an interface, by default the proxy will be a Java Dynamic Proxy. This means that only external method calls that come in through the proxy will be intercepted."
Refer https://www.baeldung.com/transaction-configuration-with-jpa-and-spring.
Following should make it work:
DBService service = ctx.getBean(DBService.class);
I've tried to add a custom behaviour to Spring Data repository, but it didn't work.
Dao:
public interface Dao extends JpaRepository<User, Long>, DaoCustom {
}
DaoCustom:
public interface DaoCustom {
User create(User user);
}
DaoCustomImpl:
#Repository
#Transactional
public class DaoCustomImpl implements DaoCustom {
#PersistenceContext
private EntityManager em;
#Override
public User create(User user) {
em.persist(user);
return user;
}
}
MainClass:
public class SpringDataJPAMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(RootConfig.class);
Dao dao = context.getBean(Dao.class);
}
}
When I run MainClass, the following exception is thrown:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property create found for type User!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at testSpringDataJPA.config.SpringDataJPAMain.main(SpringDataJPAMain.java:10)
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property create found for type User!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247)
at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398)
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378)
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:86)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 11 more
What's wrong? According to Spring's tutorial it should work fine.
For implementing your custom repository in Spring Data Repository, you have to follow Spring naming conventions. So try this:
#Repository
#Transactional
public class DaoImpl implements DaoCustom {
#PersistenceContext
private EntityManager em;
#Override
public User create(User user) {
em.persist(user);
return user;
}
}
Your custom repository implementation class name should be 'MainRepositoryClassName' + 'Impl'
i couldn't find solution for my problem anywhere.
I'm trying to make validation working in spring web flow form. I need to
set validator in configuration, however it's located in another config file
and it seems spring can't find proper bean. How can I achieve successful injection here?
As far as I know, Autowiring should inject bean into validator reference.
Maybe it has something to do with order of loading configuration classes?
WebConfig.java:
#Configuration
#Import(godziszewski.patryk.ElectronicsStore.config.FlowConfiguration.class)
#EnableWebMvc
#ComponentScan(basePackages = "godziszewski.patryk")
public class WebConfig extends WebMvcConfigurerAdapter {
....
#Bean
public LocalValidatorFactoryBean validator()
{
LocalValidatorFactoryBean lv = new LocalValidatorFactoryBean();
lv.setValidationMessageSource(messageSource());
return lv;
}
}
FlowConfiguration.java:
#Configuration
public class FlowConfiguration extends AbstractFlowConfiguration {
#Autowired
Validator validator;
....
#Bean
public FlowBuilderServices flowBuilderServices()
{
FlowBuilderServices fbs = new FlowBuilderServices();
fbs.setValidator(validator);
return fbs;
}
}
The error i'm getting:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'flowConfiguration':
Unsatisfied dependency expressed through field 'validator':
No qualifying bean of type [org.springframework.validation.Validator] found for dependency [org.springframework.validation.Validator]:
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 [org.springframework.validation.Validator] found for dependency [org.springframework.validation.Validator]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Im using spring 4.3.2.RELEASE
However, when I delete Validator dependency from FlowAdapter.class I get error :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flowBuilderServices' defined in class path resource [godziszewski/patryk/ElectronicsStore/config/FlowConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: The ViewFactoryCreator is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
at godziszewski.patryk.ElectronicsStore.config.FlowConfiguration$$EnhancerBySpringCGLIB$$b65e14d6.flowBuilderServices(<generated>)
at godziszewski.patryk.ElectronicsStore.config.FlowConfiguration.flowRegistry(FlowConfiguration.java:25)
at godziszewski.patryk.ElectronicsStore.config.FlowConfiguration$$EnhancerBySpringCGLIB$$b65e14d6.CGLIB$flowRegistry$3(<generated>)
at godziszewski.patryk.ElectronicsStore.config.FlowConfiguration$$EnhancerBySpringCGLIB$$b65e14d6$$FastClassBySpringCGLIB$$e5741e7e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at godziszewski.patryk.ElectronicsStore.config.FlowConfiguration$$EnhancerBySpringCGLIB$$b65e14d6.flowRegistry(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 24 more
Caused by: java.lang.IllegalArgumentException: The ViewFactoryCreator is required
Full FlowConfiguration class code, maybe I'm doing something wrong?
package godziszewski.patryk.ElectronicsStore.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.webflow.config.AbstractFlowConfiguration;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.executor.FlowExecutor;
import org.springframework.webflow.mvc.servlet.FlowHandlerAdapter;
import org.springframework.webflow.mvc.servlet.FlowHandlerMapping;
#Configuration
public class FlowConfiguration extends AbstractFlowConfiguration {
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder()
.setBasePath("/WEB-INF/flows")
.setFlowBuilderServices(flowBuilderServices())
.addFlowLocationPattern("/**/*-flow.xml")
.build();
}
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry()).build();
}
#Bean
public FlowHandlerMapping flowHandlerMapping()
{
System.out.println("flowconfig");
FlowHandlerMapping fh = new FlowHandlerMapping();
fh.setFlowRegistry(flowRegistry());
return fh;
}
#Bean
public FlowHandlerAdapter flowHandlerAdapter()
{
FlowHandlerAdapter fh = new FlowHandlerAdapter();
fh.setFlowExecutor(flowExecutor());
return fh;
}
#Bean
public FlowBuilderServices flowBuilderServices()
{
FlowBuilderServices fbs = new FlowBuilderServices();
//fbs.setValidator(validator);
return fbs;
}
}
If i delete .setFlowBuilderServices(flowBuilderServices()) method, everything works fine
EDIT: I managed to get this working by deleting #Configuration annotation form flow config class, now it looks like this:
//#Configuration
public class FlowConfiguration extends AbstractFlowConfiguration {
#Autowired
Validator validator;
...
#Bean
public FlowBuilderServices flowBuilderServices()
{
System.out.println(validator.toString());
FlowBuilderServices fbs = new FlowBuilderServices();
fbs.setValidator(validator);
return fbs;
}
And now I can use injected LocalValidatorBean in this class.
I interpret that eventually you need a FlowBuilderServices which has a reference to Validator bean.
This can be achieved by using the Autowired tag inside FlowBuilderServices
public class FlowBuilderServices{
#Autowired
Validator validator
...
}
And then in FlowConfiguration you just need to define the bean
#Bean
public class FlowBuilderServices flowBuilderServices()
{
FlowBuilderServices fbs = new FlowBuilderServices();
return fbs;
}
When I start my application using springboot, an exception occurs. I have no idea about it.
#Bean
#ConfigurationProperties(prefix="master.datasource")
public DataSource master() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
#Bean
#ConfigurationProperties(prefix = "slave1.datasource")
public DataSource slave1() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
#Bean
public DynamicDataSource dataSource() {
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setMaster(master());
List<DataSource> slaves = new ArrayList<DataSource>();
slaves.add(slave1());
dataSource.setSlaves(slaves);
return dataSource;
}
Here is DynamicDataSource class structure
public class DynamicDataSource extends AbstractRoutingDataSource {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private AtomicInteger counter = new AtomicInteger();
private DataSource master;
private List<DataSource> slaves;
Caused by:
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'dataSource': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:356)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1066)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.init(DataSourceInitializer.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:354)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:305)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
Try to switch off Spring Boot's autoconfiguration of DataSources. Add the following to your main #Configuration class:
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
This question already has answers here:
java.lang.ClassNotFoundException: org.aspectj.util.PartialOrder$PartialComparable
(4 answers)
Closed 4 years ago.
i created an app based on spring boot and spring boot data , so i want to use
HSQLDB in memory
This is my Application Class :
package boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication()
public class Application {
public static void main(String[] args) {
SpringApplication.run(Config.class);
}
}
and this is Config class :
#Configuration
#EnableAutoConfiguration
#EnableJpaRepositories
#ComponentScan(basePackages = {"controller", "dao", "service"})
#EnableTransactionManagement
class Config {
#Bean(name = "dataSource")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
#Bean(name = "entityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.HSQL);
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(getClass().getPackage().getName());
factory.setDataSource(dataSource());
return factory;
}
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
}
as you khnow in the these three packages "controller", "dao", "service" there are
some #Autowired
when i run the Application, i got this error :
Error creating bean with name 'taskController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private service.TaskManager controller.TaskController.taskManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskManagerImpl' defined in file [D:\JavaSe\restAng\target\classes\service\impl\TaskManagerImpl.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/util/PartialOrder$PartialComparable
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
this is my TaskController
#RestController
public class TaskController {
#Autowired
private TaskManager taskManager;
#RequestMapping(value = "/tasks", method = RequestMethod.GET, headers = "Accept=application/json")
public List<Task> getAllTasks() {
return taskManager.getAll();
}
}
What's wrong with it ?
You are missing aspectjweaver. You need to add it to your dependencies.
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>