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.
Related
When I inject my sessionFactory Bean using Java based configuration for Hibernate my bean is null and I don't know why. I've scoured the internet for answers but couldn't find any. I've looked over my configuration and compared it against guides online. Any answers are greatly appreciated.
Here's the exact error
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.hibernate.SessionFactory.getCurrentSession()" because "com.example.demo.DemoApplication.sessionFactory" is null
Here's my code
HibernateConfiguration File, Annotation based.
#Configuration
#EnableTransactionManagement
public class HibernateConfig {
#Bean
#Scope //By default the scope is singleton which means that the IOC will only create a single instance of the bean and return that one reference for subsequent calls for that bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan( packagesToScan()); //Model packages to scan
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
//Direct Physical Connection Information
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/demo");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
//List of Entities to scan
#Bean
public String [] packagesToScan() {
return new String [] { "com.example.demo.Entities.Student" };
}
//Configures properties of our hibernate configuration, dialect,
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
hibernateProperties.setProperty("show_sql", "true");
hibernateProperties.setProperty("current_session_context_class", "thread");
return hibernateProperties;
}
}
My Main application where I'm attempting to inject my Session Factory singleton bean for use.
#SpringBootApplication
public class DemoApplication {
#Autowired
static SessionFactory sessionFactory;
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class, HibernateConfig.class); // Makes the sessionFactory bean known to the IOC
Session currentSession = sessionFactory.getCurrentSession();
(( ConfigurableApplicationContext )ctx).close(); //Close the applicationContext
SpringApplication.run(DemoApplication.class, args);
}
}
The container gets started when SpringApplication.run invokes. I think before all of this an injection and the usage of that bean does not makes sense. First you need to fire Springapplication and then the rest of the business logic.
Your bean isn't scanned and initialize at the moment of the injection.
Possible solution :
#Component
public class IOCAfterInitializationListener implements ApplicationListener<ContextRefreshedEvent> {
#Autowired
static SessionFactory sessionFactory;
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Session currentSession = sessionFactory.getCurrentSession();
//do whatever you want
}
}
I'm currently learning Spring and Hibernate. I have a StudentDAOImpl class that contains all my database queries. I want to get an instance of this bean in my main function and run the query methods there all in my main function for testing. I'm trying to do this by calling the getBean() method because the name of the bean is the class but first letter is lowercase if I'm not mistaken. The compiler is giving me this error
Exception in thread "main org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'studentDAOImpl' available**
Why can't Spring find my StudentDAOImpl bean? Thank you for your time in reading this post.
Here's my code
Main Function
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class,HibernateConfig.class); // Makes the sessionFactory bean known to the IOC
StudentDAOImpl student = (StudentDAOImpl)ctx.getBean("studentDAOImpl");
Student aStudent = new Student("dasdasdas","dasdadas","dsadasdasda#gmail.com");
student.addStudent(aStudent);
(( ConfigurableApplicationContext )ctx).close(); //Close the applicationContext
SpringApplication.run(DemoApplication.class, args);
}
StudentDAOImpl Class
#Repository //Sets up componenent scanning for DI for our services
public class StudentDAOImpl implements StudentDAO{
#Autowired
SessionFactory sessionFactory;
//Queries Ommited from post for space saving purposes
}
HibernateConfiguration File
#Configuration
#EnableTransactionManagement
public class HibernateConfig {
#Bean(name = "sessionFactory")
#Scope("singleton")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(packagesToScan());
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/demo");
dataSource.setUsername("root");
dataSource.setPassword("danielL45");
return dataSource;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private String[] packagesToScan(){
return new String[] {
"com.example.demo.Entities.Student"
};
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
hibernateProperties.setProperty("current_session_context_class", "thread");
return hibernateProperties;
}
}
Use this:
StudentDAOImpl student = ctx.getBean(StudentDAOImpl.class)
This is a more secure way to get the bean that we need, since we may have only one bean with this class, using a string to select a Spring Bean has a propability of not working when not writing the name correctly.
I'm trying to convert a Spring 4 project to use HibernateTransactionManager to manage the transactions, but transactional services throw this exception:
org.hibernate.HibernateException: createSQLQuery is not valid without
active transaction
I've searched on google, and 80 different people have 80 different ways of doing it. I've tried them all, and either they don't work or they require using EntityManager instead of Hibernate Sessions. Since I'm converting existing code that uses Hibernate sessions, things would be far easier if I could get them to work. How do I get rid of this exception?
Spring version: 4.2.5.RELEASE
Hibernate version: 5.1.0.Final
Hikari version: 2.7.6
JDK version: 1.8.0_161
DataSource config:
#Configuration
public class DataSourceConfig {
#Bean
public DataSource dataSource() {
// return a Hikari connection pool as the data source
try {
HikariDataSource bean = new HikariDataSource();
// set connection pool and JDBC properties
return bean;
} catch (Exception e) {
throw new RuntimeException("could create data source", e);
}
}
}
Session factory config:
#Configuration
public class SessionFactoryConfig {
#Autowired
private DataSource dataSource;
#Bean
public LocalSessionFactoryBean sessionFactory() {
// create a session factory
try {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
// set Hibernate properties
bean.setDataSource(dataSource);
bean.setPackagesToScan(packagesToScan);
bean.setHibernateProperties(properties);
bean.afterPropertiesSet(); // tried without this line as well
return bean;
} catch (Exception e) {
throw new RuntimeException("could not create session factory", e);
}
}
}
Transaction config:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.mydomain.*")
public class TransactionConfig {
#Autowired
private SessionFactory sessionFactory;
#Bean
public PlatformTransactionManager transactionManager() {
HibernateTransactionManager bean = new HibernateTransactionManager(sessionFactory);
// bean.setHibernateManagedSession(true); // similar exception when set
bean.afterPropertiesSet(); // tried without this line as well
return bean;
}
}
Service:
#Service
#Transactional // tried using only the #Transactional on the method
public class TestTransactionService {
#Autowired
private SessionFactory sessionFactory;
#Transactional // tried using only the #Transactional on the class
public String get(String key) {
Session session = sessionFactory.getCurrentSession();
// the below line throws the exception!
SQLQuery q = session.createSQLQuery("SELECT value FROM test_transaction WHERE key = :key");
q.setParameter("key", key);
q.addScalar("value", StringType.INSTANCE);
String out = (String)q.uniqueResult();
return out;
}
}
Any ideas? I hope so because I'm out.
Buried in our settings was this innocent-looking one, in there since the initial git checkin of our project, so I cannot find out who put it in (they're lucky):
hibernate.current_session_context_class = thread
Since no one knew what this setting was for, no one dared touch it since then. This breaks Spring managed transactions, and had no business being in there.
Let's this be a lesson, boys and girls: if you're trying to get something to work, DON'T just fiddle with settings when you don't know what they are. It will come back to bite you in the ass--sometimes years later. And then I will come find you and get you.
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() {
...
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);