spring injection bean which inherits from interface - java

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);

Related

UnsatisfiedDependencyException after changing Entity annotated classes

I am writing a web app using Spring and Hibernate.
I get this exception:
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'trustDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.cybertrust.tms.config.DemoAppConfig: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
....
The configuration I'm using was working fine, until I refactored the classes in the Entities package i.e. the #Entity annotated classes that are mapped in a mysql database. I didn't change anything in my configuration or DAO where the exception occurs. So I really can't trace the problem.
My configuration class:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.cybertrust.tms")
#PropertySource({ "classpath:persistence-mysql.properties" })
#PropertySource({ "classpath:model.properties" })
public class DemoAppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factories
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
TrustModel model() {
return new TrustModel();
}
/*#Bean
#Scope("prototype")
Trust trust() {
return new Trust();
}*/
}
DAO implementation class:
#Repository
public class TrustDAOImpl implements TrustDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public TrustAssessments getDeviceTrust(int id) {
//Session currentSession = sessionFactory.getCurrentSession();
//TrustAssessments trust = currentSession.get(TrustAssessments.class, id);
return null;
}
}
In the DAO the commented out lines are just to make sure that the Entity TrustAssessments doesn't create some kind of problem.
EDIT
As #trim24 pointed out in his comment, I checked the end of the stack trace. However I was still not able to pinpoint the problem. The exception at the end of the stack trace is this:
Nov 24, 2019 10:23:40 AM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/tms-rest] threw load() exception
java.lang.NullPointerException
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:814)
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:256)
....
I also tried deleting all the Entity classes and kept only configuration, service and DAO, and I get the same exceptions. So the refactoring of the Entity classes really didn't have anything to do with this.

Do not register the component if there are no dependent beans using spring-boot-starter

I create spring-boot-starter, which registers some bean:
#Configuration
#EnableConfigurationProperties(ClusterJProperties.class)
#ConditionalOnProperty(prefix = "clusterj", name = {"connectString", "dataBaseName"})
public class ClusterJAutoConfiguration {
private final ClusterJProperties clusterJConfigProperties;
#Autowired
public ClusterJAutoConfiguration(ClusterJProperties clusterJConfigProperties) {
this.clusterJConfigProperties = clusterJConfigProperties;
}
#Bean
#ConditionalOnMissingBean
public SessionFactory sessionFactory() {
Properties clusterJProperties = new Properties();
clusterJProperties.setProperty("com.mysql.clusterj.connectstring", clusterJConfigProperties.getConnectString());
clusterJProperties.setProperty("com.mysql.clusterj.database", clusterJConfigProperties.getDataBaseName());
clusterJProperties.putAll(clusterJConfigProperties.getProperties());
return ClusterJHelper.getSessionFactory(clusterJProperties);
}
}
I want using this starter in another module. For this, I created a component, and inject this bean there:
#Component
public class GetEntityHandler implements VoidTreeNodeHandler {
private final SessionFactory sessionFactory;
#Autowired
public GetEntityHandler(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void handle(TreeContext context, Map<String, Object> parameters) {
//do smth
}
}
But, when, properties clusterj.connectString and clusterj.connectString not present in application.yml, bean SessionFactory not create. It is ok, but GetEntityHandler want to create, and fall with error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getEntityHandler' defined in file [GetEntityHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mysql.clusterj.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
How to make my GetEnityNandler component not be created if the SessionFactory bean is not present in context?

How to I configure my own GraphDatabaseService and GraphAwareRuntime in a spring unit test with boot 2.0 and Neo4j SDN5

I'm writing some unit tests and want to use TimeTree along with Spring repositories, to auto attach event nodes to a time tree. Something like this issue, but I'm using boot 2.0 and SDN5. I think my main issue is I don't know how to set up the configuration so my repositories and my TimeTree use the same GraphDatabaseService. My #Confuration is like this:
#Configuration
public class SpringConfig {
#Bean
public SessionFactory sessionFactory() {
// with domain entity base package(s)
return new SessionFactory(configuration(), "org.neo4j.boot.test.domain");
}
#Bean
public org.neo4j.ogm.config.Configuration configuration() {
return new org.neo4j.ogm.config.Configuration.Builder()
.uri("bolt://localhost")
.build();
}
#Bean
public Session getSession() {
return sessionFactory().openSession();
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory()
.newEmbeddedDatabase(new File("/tmp/graphDb"));
}
#Bean
public GraphAwareRuntime graphAwareRuntime() {
GraphDatabaseService graphDatabaseService = graphDatabaseService();
GraphAwareRuntime runtime = GraphAwareRuntimeFactory
.createRuntime(graphDatabaseService);
runtime.registerModule(new TimeTreeModule("timetree",
TimeTreeConfiguration
.defaultConfiguration()
.withAutoAttach(true)
.with(new NodeInclusionPolicy() {
#Override
public Iterable<Node> getAll(GraphDatabaseService graphDatabaseService) {
return null;
}
#Override
public boolean include(Node node) {
return node.hasLabel(Label.label("User"));
}
})
.withRelationshipType(RelationshipType.withName("CREATED_ON"))
.withTimeZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+1")))
.withTimestampProperty("createdOn")
.withResolution(Resolution.DAY)
// .withCustomTimeTreeRootProperty("timeTreeName")
.withResolution(Resolution.HOUR), graphDatabaseService));
runtime.start();
return runtime;
}
}
And my test looks like this:
User user = new User("Michal");
user.setCreatedOn(1431937636995l);
userRepository.save(user);
GraphUnit.assertSameGraph(graphDb, "CREATE (u:User {name:'Michal', createdOn:1431937636995})," +
"(root:TimeTreeRoot)," +
"(root)-[:FIRST]->(year:Year {value:2015})," +
"(root)-[:CHILD]->(year)," +
"(root)-[:LAST]->(year)," +
"(year)-[:FIRST]->(month:Month {value:5})," +
"(year)-[:CHILD]->(month)," +
"(year)-[:LAST]->(month)," +
"(month)-[:FIRST]->(day:Day {value:18})," +
"(month)-[:CHILD]->(day)," +
"(month)-[:LAST]->(day)," +
"(day)<-[:CREATED_ON]-(u)"
);
GraphUnit.printGraph(graphDb);
graphDb.shutdown();
There's a host of errors, but I think they all stem from this one:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.data.repository.support.Repositories]:
Factory method 'repositories' threw exception; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'userRepository': Unsatisfied dependency
expressed through method 'setSession' parameter 0; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type 'org.neo4j.ogm.session.Session' available:
expected single matching bean but found 2: getSession,
org.springframework.data.neo4j.transaction.SharedSessionCreator#0
It is because the configuration class redefines some beans already automatically configured by Spring boot (here the Session).
So spring injection does not know how to choose between the 2.
Removing the getSession() should help.
A second thing is that your SessionFactory has to use the embedded DB setup in the graphDatabaseService() method. For this, configure an embedded driver with the existing database.
Summary config that should work fine for you :
#Bean
public SessionFactory sessionFactory() {
EmbeddedDriver driver = new EmbeddedDriver(graphDatabaseService());
return new SessionFactory(driver, "org.neo4j.boot.test.domain");
}
#Bean
public PlatformTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
}
#Bean
public GraphAwareRuntime graphAwareRuntime() {
...

Is there an unresolvable circular reference

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})

spring data mongo - No bean named 'mongoTemplate' is defined

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);
}
}

Categories