Facing issue with JPA Hikari Transaction Mangaement - java

I am using JPA , HikariPool to add entries in DB .
I am facing issue while saving the transaction .
Here is my main class
package com.vish.jpa_demo;
import com.vish.jpa_demo.config.AppConfig;
import com.vish.jpa_demo.model.Laptop;
import com.vish.jpa_demo.model.Student;
import com.vish.jpa_demo.service.DBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
#Slf4j
#SpringBootApplication
public class JpaDemoApplication
{
public static void main(String[] args)
{
log.info("Starting Main");
SpringApplication.run(JpaDemoApplication.class, args);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JpaDemoApplication.class);
Student s = new Student("Vish");
Laptop laptop = new Laptop("HP");
s.setLaptop(laptop);
DBService dbService =applicationContext.getBean(DBService.class);
try
{
dbService.addLaptop(laptop);
dbService.addStudent(s);
laptop.setBrand("Apple");
dbService.addLaptop(laptop);
}
catch (Exception e)
{
e.printStackTrace();
}
log.info("Exiting Main");
}
}
Here is my AppConfig
package com.vish.jpa_demo.config;
import com.vish.jpa_demo.service.DBService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#EnableTransactionManagement
#Configuration
public class AppConfig
{
#Autowired
private Environment env;
#Bean
public JpaVendorAdapter getJpaVendorAdapter()
{
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setShowSql(true);
jpaVendorAdapter.setGenerateDdl(false);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.HSQLDialect");
return jpaVendorAdapter;
}
#Bean
public DataSource getHikariDataSource()
{
final HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("XXXXX");
dataSource.setPassword("XXXX");
dataSource.setAutoCommit(false);
//dataSource.setMinEvictableIdleTimeMillis(1000);
//dataSource.setCacheState(false);s
dataSource.setConnectionTimeout(31000);
dataSource.setIdleTimeout(30000);
dataSource.setMaximumPoolSize(2);
dataSource.setMinimumIdle(0);
dataSource.setConnectionTimeout(60000);
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityMangerFactory()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(getHikariDataSource());
entityManagerFactoryBean.setJpaVendorAdapter(getJpaVendorAdapter());
entityManagerFactoryBean.setJpaProperties(DBProperties());
entityManagerFactoryBean.setPersistenceUnitName("com.vish.jpa_demo");
entityManagerFactoryBean.setPackagesToScan("com.vish.jpa_demo.model");
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager()
{
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(getEntityMangerFactory().getNativeEntityManagerFactory());
transactionManager.setDataSource(getHikariDataSource());
return transactionManager;
}
private final Properties DBProperties()
{
final Properties hibernateProperties = new Properties();
hibernateProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
//hibernateProperties.setProperty("hibernate.current_session_context_class","org.springframework.orm.hibernate5.SpringSessionContext");
hibernateProperties.setProperty("hibernate.current_session_context_class","org.hibernate.context.internal.ThreadLocalSessionContext");
return hibernateProperties;
}
}
Here is my DaoImpl Class .
Here I am trying to add one object .
Transaction is already started in Service class and I am using the same in Dao
package com.vish.jpa_demo.dao;
import com.vish.jpa_demo.model.Laptop;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
#Slf4j
#Repository
#Data
public class LaptopDaoImpl implements ILaptopDao
{
private Session session = null;
#Autowired
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager ;
private void setEntityMangerFactoryCurrentSession()
{
if ( this.session == null )
{
//this.session = this.entityManagerFactory.createEntityManager().unwrap(Session.class).getSessionFactory().openSession();
this.session = this.entityManagerFactory.createEntityManager().unwrap(Session.class).getSessionFactory().getCurrentSession();
}
}
#Override
public void addLaptop(Laptop laptop)
{
log.info("Adding Laptop " + laptop.getBrand());
setEntityMangerFactoryCurrentSession();
this.session.save(laptop);
}
#Override
public Laptop getLaptopDetailsByName(String name)
{
Laptop invalidlaptop = null ;
try
{
setEntityMangerFactoryCurrentSession();
String myQry = "from Laptop where brand = :bname";
Query query = session.createQuery(myQry,Laptop.class);
query.setParameter("bname",name);
query.setFetchSize(1);
ScrollableResults scrollableResults = query.setReadOnly(true).scroll(ScrollMode.FORWARD_ONLY);
while(true)
{
for (;scrollableResults.next(); )
{
List<Object> objectList = Arrays.asList(scrollableResults.get());
Optional<Laptop> laptop = objectList
.stream()
.map(e -> (Laptop) e )
.filter(e2 -> e2.getBrand().equalsIgnoreCase(name))
.findFirst();
return laptop.orElse(invalidlaptop);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return invalidlaptop;
}
}
Here is my Service Class
package com.vish.jpa_demo.service;
import com.vish.jpa_demo.dao.ILaptopDao;
import com.vish.jpa_demo.dao.IStudentDao;
import com.vish.jpa_demo.model.Laptop;
import com.vish.jpa_demo.model.Student;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
#Data
#Slf4j
#Component
public class DBService
{
private Session session = null;
#Autowired(required = false )
private SessionFactory sessionFactory;
#Autowired
private IStudentDao studentDao;
#Autowired
private ILaptopDao laptopDao;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void addStudent(Student student) throws Exception
{
try
{
studentDao.addStudent(student);
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
public void addLaptop(Laptop laptop) throws Exception
{
try
{
laptopDao.addLaptop(laptop);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Actual Error
"C:\Program Files\Java\jdk1.8.0_231\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:57158,suspend=y,server=n -javaagent:C:\Users\VISHBA~1\AppData\Local\Temp\captureAgent251jars\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_231\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\rt.jar;F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo\target\classes;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.4.1\spring-boot-starter-data-jpa-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.4.1\spring-boot-starter-aop-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-aop\5.3.2\spring-aop-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\aspectj\aspectjweaver\1.9.6\aspectjweaver-1.9.6.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.4.1\spring-boot-starter-jdbc-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-jdbc\5.3.2\spring-jdbc-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\jakarta\transaction\jakarta.transaction-api\1.3.3\jakarta.transaction-api-1.3.3.jar;C:\Users\VIsh bade\.m2\repository\jakarta\persistence\jakarta.persistence-api\2.2.3\jakarta.persistence-api-2.2.3.jar;C:\Users\VIsh bade\.m2\repository\org\hibernate\hibernate-core\5.4.25.Final\hibernate-core-5.4.25.Final.jar;C:\Users\VIsh bade\.m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;C:\Users\VIsh bade\.m2\repository\net\bytebuddy\byte-buddy\1.10.18\byte-buddy-1.10.18.jar;C:\Users\VIsh bade\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\VIsh bade\.m2\repository\org\jboss\jandex\2.1.3.Final\jandex-2.1.3.Final.jar;C:\Users\VIsh bade\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\VIsh bade\.m2\repository\org\dom4j\dom4j\2.1.3\dom4j-2.1.3.jar;C:\Users\VIsh bade\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.2.Final\hibernate-commons-annotations-5.1.2.Final.jar;C:\Users\VIsh bade\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.3\jaxb-runtime-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\org\glassfish\jaxb\txw2\2.3.3\txw2-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.11\istack-commons-runtime-3.0.11.jar;C:\Users\VIsh bade\.m2\repository\com\sun\activation\jakarta.activation\1.2.2\jakarta.activation-1.2.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\data\spring-data-jpa\2.4.2\spring-data-jpa-2.4.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\data\spring-data-commons\2.4.2\spring-data-commons-2.4.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-orm\5.3.2\spring-orm-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-context\5.3.2\spring-context-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-expression\5.3.2\spring-expression-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-tx\5.3.2\spring-tx-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-beans\5.3.2\spring-beans-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-aspects\5.3.2\spring-aspects-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\projectlombok\lombok\1.18.16\lombok-1.18.16.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter\2.4.1\spring-boot-starter-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot\2.4.1\spring-boot-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.4.1\spring-boot-autoconfigure-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.4.1\spring-boot-starter-logging-2.4.1.jar;C:\Users\VIsh bade\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\VIsh bade\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\VIsh bade\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.13.3\log4j-to-slf4j-2.13.3.jar;C:\Users\VIsh bade\.m2\repository\org\apache\logging\log4j\log4j-api\2.13.3\log4j-api-2.13.3.jar;C:\Users\VIsh bade\.m2\repository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;C:\Users\VIsh bade\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\Users\VIsh bade\.m2\repository\org\yaml\snakeyaml\1.27\snakeyaml-1.27.jar;C:\Users\VIsh bade\.m2\repository\jakarta\xml\bind\jakarta.xml.bind-api\2.3.3\jakarta.xml.bind-api-2.3.3.jar;C:\Users\VIsh bade\.m2\repository\jakarta\activation\jakarta.activation-api\1.2.2\jakarta.activation-api-1.2.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-core\5.3.2\spring-core-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\org\springframework\spring-jcl\5.3.2\spring-jcl-5.3.2.jar;C:\Users\VIsh bade\.m2\repository\com\zaxxer\HikariCP\2.2.5\HikariCP-2.2.5.jar;C:\Users\VIsh bade\.m2\repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;C:\Users\VIsh bade\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;C:\Users\VIsh bade\.m2\repository\mysql\mysql-connector-java\8.0.13\mysql-connector-java-8.0.13.jar;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.2.1\lib\idea_rt.jar" com.vish.jpa_demo.JpaDemoApplication
Connected to the target VM, address: '127.0.0.1:57158', transport: 'socket'
08:48:32.958 [main] INFO com.vish.jpa_demo.JpaDemoApplication - Starting Main
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2020-12-17 08:48:33.751 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Starting JpaDemoApplication using Java 1.8.0_231 on LAPTOP-SDUPSP61 with PID 5184 (F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo\target\classes started by VIsh bade in F:\Java\VD_program\java_prog\SpringBoot_JPA_Hikari\jpa_demo)
2020-12-17 08:48:33.753 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : No active profile set, falling back to default profiles: default
2020-12-17 08:48:33.910 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Started JpaDemoApplication in 0.736 seconds (JVM running for 1.33)
2020-12-17 08:48:34.718 INFO 5184 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: com.vish.jpa_demo]
2020-12-17 08:48:34.826 INFO 5184 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-17 08:48:35.019 INFO 5184 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-17 08:48:35.370 INFO 5184 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariCP pool HikariPool-0 is starting.
2020-12-17 08:48:36.133 INFO 5184 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-12-17 08:48:36.610 INFO 5184 --- [ main] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.vish.jpa_demo.model.Laptop (class must be instantiated by Interceptor)
2020-12-17 08:48:36.864 INFO 5184 --- [ main] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.vish.jpa_demo.model.Student (class must be instantiated by Interceptor)
2020-12-17 08:48:36.992 INFO 5184 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'com.vish.jpa_demo'
2020-12-17 08:48:50.258 INFO 5184 --- [ main] com.vish.jpa_demo.dao.LaptopDaoImpl : Adding Laptop HP
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.LaptopDaoImpl.addLaptop(LaptopDaoImpl.java:51)
at com.vish.jpa_demo.service.DBService.addLaptop(DBService.java:61)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addLaptop(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:37)
Disconnected from the target VM, address: '127.0.0.1:57158', transport: 'socket'
2020-12-17 08:51:03.970 INFO 5184 --- [ main] com.vish.jpa_demo.dao.StudentDaoImpl : Adding Student Vish
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.StudentDaoImpl.addStudent(StudentDaoImpl.java:44)
at com.vish.jpa_demo.service.DBService.addStudent(DBService.java:46)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addStudent(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:38)
2020-12-17 08:51:03.975 INFO 5184 --- [ main] com.vish.jpa_demo.dao.LaptopDaoImpl : Adding Laptop Apple
org.hibernate.HibernateException: Calling method 'save' is not valid without an active transaction (Current status: NOT_ACTIVE)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:347)
at com.sun.proxy.$Proxy38.save(Unknown Source)
at com.vish.jpa_demo.dao.LaptopDaoImpl.addLaptop(LaptopDaoImpl.java:51)
at com.vish.jpa_demo.service.DBService.addLaptop(DBService.java:61)
at com.vish.jpa_demo.service.DBService$$FastClassBySpringCGLIB$$ffafa2f0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.vish.jpa_demo.service.DBService$$EnhancerBySpringCGLIB$$5cfb11dd.addLaptop(<generated>)
at com.vish.jpa_demo.JpaDemoApplication.main(JpaDemoApplication.java:40)
2020-12-17 08:51:03.980 INFO 5184 --- [ main] com.vish.jpa_demo.JpaDemoApplication : Exiting Main
Process finished with exit code 0
Entire code is available at https://github.com/vishy-wisy/Java/tree/main/jpa_demo
Thanks in advance !

Related

Controller Method is not getting triggered

I have recently started exploring Spring boot. I am following https://www.bezkoder.com/spring-boot-jdbctemplate-postgresql-example/ documentation.
I have created all files as instructed in the documentation.
Here goes my code:
******AppApplication.java
`package com.triveni.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}`
***** IProductRepository *****
`package com.triveni.repository;
import com.triveni.models.ProductModel;
import java.util.List;
public interface IProductRepository {
int create(ProductModel productModel);
int update (ProductModel productModel);
ProductModel findById(int id);
List<ProductModel> findAll();
List<ProductModel> findByActive(boolean active);
}`
***** ProductModel.java *****
package com.triveni.models;
public class ProductModel {
private int productId;
private String productName;
private int cost;
private Boolean active;
private int descriptionId;
public ProductModel(int productId, String productName, int cost, Boolean active, int descriptionId){
this.productId = productId;
this.productName = productName;
this.cost = cost;
this.active = active;
this.descriptionId = descriptionId;
}
public void setProductId(int productId){
this.productId = productId;
}
public long getProductId(){
return productId;
}
public void setProductName(String productName){
this.productName = productName;
}
public String getProductName(){
return productName;
}
public void setCost(int cost) {
this.cost = cost;
}
public int getCost() {
return cost;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getActive() {
return active;
}
public void setDescriptionId(int descriptionId) {
this.descriptionId = descriptionId;
}
public int getDescriptionId() {
return descriptionId;
}
}
*** Product Repository *****
package com.triveni.data;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class ProductRepository implements IProductRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public int create(ProductModel productModel) {
return jdbcTemplate.update("INSERT INTO public.product(\n" +
"\t\"productId\", \"productName\", cost, \"DescriptionId\", active)\n" +
"\tVALUES (?, ?, ?, ?, ?);",new Object[]{productModel.getProductId(),productModel.getProductName(),
productModel.getCost(), productModel.getDescriptionId(),productModel.getActive()});
}
#Override
public int update(ProductModel productModel) {
return 0;
}
#Override
public ProductModel findById(int id) {
return null;
}
#Override
public List<ProductModel> findAll() {
return jdbcTemplate.query("SELECT \"productId\", \"productName\", cost, \"DescriptionId\", active\n" +
"\tFROM public.product",BeanPropertyRowMapper.newInstance(ProductModel.class));
}
#Override
public List<ProductModel> findByActive(boolean active) {
return null;
}
}
***** ProductController.java *****
package com.triveni.controllers;
import java.util.ArrayList;
import java.util.List;
import com.triveni.data.ProductRepository;
import com.triveni.models.ProductModel;
import com.triveni.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/product")
public ResponseEntity<List<ProductModel>> getAllProducts(){
try{
List<ProductModel> products = new ArrayList<ProductModel>();
productRepository.findAll().forEach(products::add);;
return new ResponseEntity<>(products, HttpStatus.OK);
}catch (Exception e){
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
My Project Folder Structure
I am getting following error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 27 13:51:39 IST 2022
There was an unexpected error (type=Not Found, status=404).
Any help will be highly appreciated.
*Output
/Users/chhayatiwari/Library/Java/JavaVirtualMachines/openjdk-19.0.1/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=51857:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-web/3.0.1/spring-boot-starter-web-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter/3.0.1/spring-boot-starter-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot/3.0.1/spring-boot-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/3.0.1/spring-boot-autoconfigure-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-logging/3.0.1/spring-boot-starter-logging-3.0.1.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-classic/1.4.5/logback-classic-1.4.5.jar:/Users/chhayatiwari/.m2/repository/ch/qos/logback/logback-core/1.4.5/logback-core-1.4.5.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.19.0/log4j-to-slf4j-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/apache/logging/log4j/log4j-api/2.19.0/log4j-api-2.19.0.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/jul-to-slf4j/2.0.6/jul-to-slf4j-2.0.6.jar:/Users/chhayatiwari/.m2/repository/jakarta/annotation/jakarta.annotation-api/2.1.1/jakarta.annotation-api-2.1.1.jar:/Users/chhayatiwari/.m2/repository/org/yaml/snakeyaml/1.33/snakeyaml-1.33.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-json/3.0.1/spring-boot-starter-json-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.14.1/jackson-databind-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.14.1/jackson-annotations-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.14.1/jackson-core-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.14.1/jackson-datatype-jdk8-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.14.1/jackson-datatype-jsr310-2.14.1.jar:/Users/chhayatiwari/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.14.1/jackson-module-parameter-names-2.14.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/3.0.1/spring-boot-starter-tomcat-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/10.1.4/tomcat-embed-core-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/10.1.4/tomcat-embed-el-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/10.1.4/tomcat-embed-websocket-10.1.4.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-web/6.0.3/spring-web-6.0.3.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-observation/1.10.2/micrometer-observation-1.10.2.jar:/Users/chhayatiwari/.m2/repository/io/micrometer/micrometer-commons/1.10.2/micrometer-commons-1.10.2.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-webmvc/6.0.3/spring-webmvc-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-aop/6.0.3/spring-aop-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-context/6.0.3/spring-context-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-expression/6.0.3/spring-expression-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/slf4j/slf4j-api/2.0.6/slf4j-api-2.0.6.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-core/6.0.3/spring-core-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jcl/6.0.3/spring-jcl-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-data-jdbc/3.0.1/spring-boot-starter-data-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/3.0.1/spring-boot-starter-jdbc-3.0.1.jar:/Users/chhayatiwari/.m2/repository/com/zaxxer/HikariCP/5.0.1/HikariCP-5.0.1.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-jdbc/3.0.0/spring-data-jdbc-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-relational/3.0.0/spring-data-relational-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/data/spring-data-commons/3.0.0/spring-data-commons-3.0.0.jar:/Users/chhayatiwari/.m2/repository/org/postgresql/postgresql/42.5.1/postgresql-42.5.1.jar:/Users/chhayatiwari/.m2/repository/org/checkerframework/checker-qual/3.5.0/checker-qual-3.5.0.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-jdbc/5.3.22/spring-jdbc-5.3.22.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-beans/6.0.3/spring-beans-6.0.3.jar:/Users/chhayatiwari/.m2/repository/org/springframework/spring-tx/6.0.3/spring-tx-6.0.3.jar com.triveni.app.AppApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.1)
2022-12-27T20:17:11.351+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Starting AppApplication using Java 19.0.1 with PID 3695 (/Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app/target/classes started by chhayatiwari in /Users/chhayatiwari/Desktop/Work/TriveniApp-Service/app)
2022-12-27T20:17:11.353+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-27T20:17:11.664+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-12-27T20:17:11.671+05:30 INFO 3695 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JDBC repository interfaces.
2022-12-27T20:17:11.919+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-12-27T20:17:11.924+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-27T20:17:11.925+05:30 INFO 3695 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.4]
2022-12-27T20:17:11.972+05:30 INFO 3695 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-27T20:17:11.973+05:30 INFO 3695 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 589 ms
2022-12-27T20:17:12.162+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-12-27T20:17:12.282+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6680f714
2022-12-27T20:17:12.283+05:30 INFO 3695 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-12-27T20:17:12.343+05:30 INFO 3695 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-12-27T20:17:12.348+05:30 INFO 3695 --- [ main] com.triveni.app.AppApplication : Started AppApplication in 1.206 seconds (process running for 1.435)
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-12-27T20:19:18.599+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-12-27T20:19:18.604+05:30 INFO 3695 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
try to add this to annotation #CrossOrigin("*") after #RestController.
I believe you are just launching the spring application and on launch, this error shows up. In order to test your URL you can type
<YOUR-URL>/app/v1/product
This should return you the Response you are looking for.
Remove ResponseEntity<List> from method and instead return a simple String and check if the method invoked or not. If it works properly then go to the next step and invoke the repository.

JPA repository .save in Netty server channelInitializer handler not working

I have initialized the socket channel in the Netty server but I have faced an issue with the handler, when I want to save the received data from the client to MySQL through JPA it can not be saved.
package com.servernetty.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ServerApplication {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(ServerApplication.class, args);
}
}
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
private final TestRepo testRepo;
#Autowired
public ServerService(#Value("${hs.host}") String host, #Value("${hs.port}") int port, TestRepo testRepo) throws Exception {
this.testRepo = testRepo;
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new NettyServerHandler());
}
});
logger.info("You are here in message server port no: " + port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} finally {
logger.info("finallllllll: " + port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private final TestRepo testrepo;
public NettyServerHandler(TestRepo testrepo) {
this.testrepo = testrepo;
}
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
log.info("before save");
try {
testrepo.save(trans);
} catch (Exception e) {
log.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
log.info("after save");
}
}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
import javax.transaction.Transactional;
import com.servernetty.server.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
The folder structure
The exception that I receive
java.lang.NullPointerException
at com.servernetty.server.handlers.NettyServerHandler.channelRead(NettyServerHandler.java:105)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:829)
In logger I receive the "before save" but nothing after that, the application stacks.
Appreciate your help
I took your code and removed all (new) and all (Constructors). It is best to let Springboot Autowire everything for you:
Pay attention to how ServerService and NettyServerHandler are implemented.
package com.example.socketchannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SocketchannelApplication {
public static void main(String[] args) {
SpringApplication.run(SocketchannelApplication.class, args);
}
}
package com.example.socketchannel.controller;
import com.example.socketchannel.service.NettyServerHandler;
import com.example.socketchannel.service.ServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ServerController {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private ServerService serverService;
}
package com.example.socketchannel.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.*;
import io.netty.channel.socket.*;
import io.netty.channel.socket.nio.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
#Service
public class ServerService {
private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
//You need to add hs.host to your properties
#Value("${hs.host:127:0.0.1}")
private String host;
//You need to add hs.port to your properties.
#Value("${hs.port:9090}")
private Integer port;
#Autowired
private NettyServerHandler nettyServerHandler;
#PostConstruct
private void init() {
EventLoopGroup booGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap().
group(booGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.localAddress("127.0.0.1", port).childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(nettyServerHandler);
}
});
logger.info("You are here in message server port no {}", port);
ChannelFuture channel = bootstrap.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("Encounterd Exception", e);
} finally {
logger.info("finallllllll: {} ", port);
booGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.example.socketchannel.service;
import com.example.socketchannel.model.TestModel;
import com.example.socketchannel.repository.TestRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
#Service
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
#Autowired
private TestRepo testRepo;
/**
* The message sent by the client will trigger
*/
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TestModel trans = new TestModel();
trans.setId(11);
trans.setTestf("d11");
trans.setTransactionType("test");
logger.info("before save");
try {
testRepo.save(trans);
} catch (Exception e) {
logger.info("tttttttttttttt" + e.toString());
e.printStackTrace();
}
logger.info("after save");
}
}
package com.example.socketchannel.repository;
import com.example.socketchannel.model.TestModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository<TestModel, Integer> {
}
package com.example.socketchannel.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "test", uniqueConstraints = #UniqueConstraint(columnNames = { "id" }, name = "TEST_UNIQUE_ID"))
public class TestModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", columnDefinition = "bigint unsigned")
private Integer id;
String testf;
#Column(name = "transaction_type")
String transactionType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTestf() {
return testf;
}
public void setTestf(String testf) {
this.testf = testf;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>socketchannel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>socketchannel</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.41.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Validating that the springboot context runs, if you do mvn clean install
package com.example.socketchannel;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class SocketchannelApplicationTests {
#Test
void contextLoads() {
}
}
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building socketchannel 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-core/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-core/maven-metadata.xml (0 B at 0.0 KB/sec)
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev-local/io/grpc/grpc-api/maven-metadata.xml
Downloading: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml
Downloaded: https://arm.lmera.ericsson.se/artifactory/proj-cv-dev/io/grpc/grpc-api/maven-metadata.xml (2 KB at 10.5 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to C:\UCA-Development\cvc-clones\services\socketchannel\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) # socketchannel ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory C:\UCA-Development\cvc-clones\services\socketchannel\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # socketchannel ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\UCA-Development\cvc-clones\services\socketchannel\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # socketchannel ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.socketchannel.SocketchannelApplicationTests
14:01:36.120 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
14:01:36.140 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
14:01:36.228 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.socketchannel.SocketchannelApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
14:01:36.251 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.example.socketchannel.SocketchannelApplicationTests], using SpringBootContextLoader
14:01:36.260 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTests-context.xml] does not exist
14:01:36.261 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.socketchannel.SocketchannelApplicationTests]: class path resource [com/example/socketchannel/SocketchannelApplicationTestsContext.groovy] does not exist
14:01:36.261 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.socketchannel.SocketchannelApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
14:01:36.262 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.socketchannel.SocketchannelApplicationTests]: SocketchannelApplicationTests does not declare any static, non-private, non-final, nested classes annotated with #Configuration.
14:01:36.351 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.socketchannel.SocketchannelApplicationTests]
14:01:36.542 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\UCA-Development\cvc-clones\services\socketchannel\target\classes\com\example\socketchannel\SocketchannelApplication.class]
14:01:36.544 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found #SpringBootConfiguration com.example.socketchannel.SocketchannelApplication for test class com.example.socketchannel.SocketchannelApplicationTests
14:01:36.788 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.example.socketchannel.SocketchannelApplicationTests]: using defaults.
14:01:36.788 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
14:01:36.823 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#38f116f6, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#5286c33a, org.springframework.test.context.event.ApplicationEventsTestExecutionListener#6e6d5d29, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#5c530d1e, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener#6c25e6c4, org.springframework.test.context.support.DirtiesContextTestExecutionListener#85e6769, org.springframework.test.context.transaction.TransactionalTestExecutionListener#c5ee75e, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#48a12036, org.springframework.test.context.event.EventPublishingTestExecutionListener#bf1ec20, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#70efb718, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#b70da4c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#4a11eb84, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener#4e858e0a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener#435fb7b5, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener#4e70a728]
14:01:36.829 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#3f07b12c testClass = SocketchannelApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#4bd1f8dd testClass = SocketchannelApplicationTests, locations = '{}', classes = '{class com.example.socketchannel.SocketchannelApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4bbf6d0e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#2415fc55, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#5e21e98f, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#7b993c65, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#6692b6c6, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#192d43ce], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with #DirtiesContext [false] with mode [null].
14:01:36.903 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.6)
2021-10-31 14:01:38.142 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : Starting SocketchannelApplicationTests using Java 11.0.7 on SE-00018098 with PID 6128 (started by ezsusmu in C:\UCA-Development\cvc-clones\services\socketchannel)
2021-10-31 14:01:38.150 INFO 6128 --- [ main] c.e.s.SocketchannelApplicationTests : No active profile set, falling back to default profiles: default
2021-10-31 14:01:41.285 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-10-31 14:01:41.439 INFO 6128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 135 ms. Found 1 JPA repository interfaces.
2021-10-31 14:01:46.495 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-10-31 14:01:47.188 INFO 6128 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-10-31 14:01:47.567 INFO 6128 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-31 14:01:47.852 INFO 6128 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-10-31 14:01:48.528 INFO 6128 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-31 14:01:49.292 INFO 6128 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-10-31 14:01:51.596 INFO 6128 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-10-31 14:01:51.617 INFO 6128 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-31 14:01:53.868 INFO 6128 --- [ main] c.e.socketchannel.service.ServerService : You are here in message server port no 9090
2021-10-31 14:01:57.647 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] REGISTERED
2021-10-31 14:01:57.651 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903] BIND: 0.0.0.0/0.0.0.0:9090
2021-10-31 14:01:57.655 INFO 6128 --- [ntLoopGroup-2-1] io.netty.handler.logging.LoggingHandler : [id: 0x23fb4903, L:/0:0:0:0:0:0:0:0:9090] ACTIVE
try to use spring-boot-starter-jdbc, you will not face the issue.

Bean of type String that could not be found

This webapp is going to work with database, but for now I've started with an easiest stub and got stuck.
I'm kinda clueless what is wrong. Overall I'm not that familiar with Spring or with how to understand and trace such errors. The only thing I understand here is that it has nothing to do with the type of a method argument. I've googled this error, looked into some answers about this kind of error here, but failed at finding the right solution.
So, I'm getting this:
:: Spring Boot :: (v2.2.5.RELEASE)
2020-05-22 15:44:36.132 INFO 17992 --- [ main] c.rinkashikachi.SpringReactApplication : Starting SpringReactApplication v0.0.1-SNAPSHOT on DESKTOP-3BPPMPQ with PID 17992 (D:\Projects\J
ava\zni\target\zni-0.0.1-SNAPSHOT.jar started by 15rin in D:\Projects\Java\zni)
2020-05-22 15:44:36.135 INFO 17992 --- [ main] c.rinkashikachi.SpringReactApplication : No active profile set, falling back to default profiles: default
2020-05-22 15:44:37.108 INFO 17992 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-05-22 15:44:37.116 INFO 17992 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-22 15:44:37.116 INFO 17992 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-22 15:44:37.166 INFO 17992 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-22 15:44:37.166 INFO 17992 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 999 ms
2020-05-22 15:44:37.241 WARN 17992 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springfram
ework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'utilController' defined in URL [jar:file:/D:/Projects/Java/zni/target/zni-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/co
m/rinkashikachi/controllers/UtilController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyExcep
tion: Error creating bean with name 'databaseMetaDataService': Unsatisfied dependency expressed through method 'getTableListBySchema' parameter 0; nested exception is org.springframework.beans.fact
ory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-05-22 15:44:37.244 INFO 17992 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-05-22 15:44:37.252 INFO 17992 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-22 15:44:37.326 ERROR 17992 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method getTableListBySchema in com.rinkashikachi.service.DatabaseMetaDataService required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.
This is where the method is.
package com.rinkashikachi.service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.repositories.ColNameEntity;
import com.rinkashikachi.service.repositories.TableNameEntity;
import java.util.ArrayList;
import java.util.List;
#Service("databaseMetaDataService")
public class DatabaseMetaDataService {
#Autowired
public List<TableNameEntity> getTableListBySchema(String schema) {
// Stub
List<TableNameEntity> names = new ArrayList<>(3);
switch(schema) {
case "ADDITIONAL":
names.add(new TableNameEntity(1L, "ADDITIONAL1"));
names.add(new TableNameEntity(2L, "ADDITIONAL2"));
names.add(new TableNameEntity(3L, "ADDITIONAL3"));
break;
case "BOOKKEEPING":
names.add(new TableNameEntity(1L, "BOOKKEEPING1"));
names.add(new TableNameEntity(2L, "BOOKKEEPING2"));
names.add(new TableNameEntity(3L, "BOOKKEEPING3"));
break;
}
return names;
}
}
And this is where I use it:
package com.rinkashikachi.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.DatabaseMetaDataService;
import com.rinkashikachi.service.repositories.TableNameEntity;
#Controller
#RequestMapping(value="/api")
public class UtilController {
private final DatabaseMetaDataService databaseMetaDataService;
#Autowired
public UtilController(DatabaseMetaDataService databaseMetaDataService) {
this.databaseMetaDataService = databaseMetaDataService;
}
#GetMapping(value="/tech")
public ResponseEntity<List<String>> getTechData(
#RequestParam(value="schema") String schema,
#RequestParam(value="table", required = false) String table,
#RequestParam(value="column", required = false) String column) {
List<TableNameEntity> entityList = databaseMetaDataService.getTableListBySchema(schema);
List<String> tables = new ArrayList<>(entityList.size());
for (TableNameEntity entity : entityList) {
tables.add(entity.toString());
System.out.println(entity);
}
return !tables.isEmpty()
? new ResponseEntity<>(tables, HttpStatus.OK)
: new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
The problem is with this code:
#Autowired
public List getTableListBySchema(String schema) {
Can you try:
package com.rinkashikachi.service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.repositories.ColNameEntity;
import com.rinkashikachi.service.repositories.TableNameEntity;
import java.util.ArrayList;
import java.util.List;
#Service("databaseMetaDataService")
public class DatabaseMetaDataService {
public List<TableNameEntity> getTableListBySchema(String schema) {
// Stub
List<TableNameEntity> names = new ArrayList<>(3);
switch(schema) {
case "ADDITIONAL":
names.add(new TableNameEntity(1L, "ADDITIONAL1"));
names.add(new TableNameEntity(2L, "ADDITIONAL2"));
names.add(new TableNameEntity(3L, "ADDITIONAL3"));
break;
case "BOOKKEEPING":
names.add(new TableNameEntity(1L, "BOOKKEEPING1"));
names.add(new TableNameEntity(2L, "BOOKKEEPING2"));
names.add(new TableNameEntity(3L, "BOOKKEEPING3"));
break;
}
return names;
}
}
package com.rinkashikachi.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import com.rinkashikachi.service.DatabaseMetaDataService;
import com.rinkashikachi.service.repositories.TableNameEntity;
#Controller
#RequestMapping(value="/api")
public class UtilController {
#Autowired
private DatabaseMetaDataService databaseMetaDataService;
#GetMapping(value="/tech")
public ResponseEntity<List<String>> getTechData(
#RequestParam(value="schema") String schema,
#RequestParam(value="table", required = false) String table,
#RequestParam(value="column", required = false) String column) {
List<TableNameEntity> entityList = databaseMetaDataService.getTableListBySchema(schema);
List<String> tables = new ArrayList<>(entityList.size());
for (TableNameEntity entity : entityList) {
tables.add(entity.toString());
System.out.println(entity);
}
return !tables.isEmpty()
? new ResponseEntity<>(tables, HttpStatus.OK)
: new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
Marking the getTableListBySchema method as Autowired tells spring to do the dependency injection here. That is why Spring looks for a bean of type Spring to autowire it to the method argument. Remove the Autowired annotation from that method.
As a side-note, if you are developing an api. You should be using the #RestController not #Controller

Spring boot - Try to authenticate user from mySQL DB - A granted authority textual representation is required

2018-10-17 20:05:37.715 ERROR 15968 --- [nio-8090-exec-3] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: A granted authority textual representation is required
Here is my SecurityConfig:
package com.project.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#ComponentScan(basePackages= {"com.project.*"})
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled=true)
#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAppUserDetailsService myAppUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/app/secure/**").hasAnyRole("ADMIN","USER")
.and().formLogin() //login configuration
.loginPage("/app/login")
.loginProcessingUrl("/app-login")
.usernameParameter("userName")
.passwordParameter("password")
.defaultSuccessUrl("/app/secure/temployee-details")
.and().logout() //logout configuration
.logoutUrl("/app-logout")
.logoutSuccessUrl("/app/login")
.and().exceptionHandling() //exception handling configuration
.accessDeniedPage("/app/error");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(myAppUserDetailsService).passwordEncoder(passwordEncoder);
}
}
And UserDetailsService:
package com.project.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.project.dao.IUserInfoDAO;
import com.project.entity.UserInfo;
#ComponentScan(basePackages= {"com.project.*"})
#Service
public class MyAppUserDetailsService implements UserDetailsService {
#Autowired
private IUserInfoDAO userInfoDAO;
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
activeUserInfo.getPassword(), Arrays.asList(authority));
return userDetails;
}
}
UserInfoDao:
package com.project.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.project.entity.TEmployee;
import com.project.entity.UserInfo;
#ComponentScan(basePackages= {"com.project.*"})
#Repository
#Transactional
public class UserInfoDAO implements IUserInfoDAO {
#PersistenceContext
private EntityManager entityManager;
public UserInfo getActiveUser(String userName) {
UserInfo activeUserInfo = new UserInfo();
short enabled = 1;
List<?> list = entityManager.createQuery("SELECT u FROM UserInfo u WHERE userName=?1 and enabled=?2")
.setParameter(1, userName).setParameter(2, enabled).getResultList();
if(!list.isEmpty()) {
activeUserInfo = (UserInfo)list.get(0);
}
return activeUserInfo;
}
#SuppressWarnings("unchecked")
#Override
public List<TEmployee> getAllUserEmployees() {
String hql = "FROM TEmployee as t ORDER BY t.employee_id";
return (List<TEmployee>) entityManager.createQuery(hql).getResultList();
}
}
I really don't understand why I still received A granted authority textual representation is required. I've added a proper role to the 'role' column in my database: ROLE_ADMIN or ROLE_USER and everything seems to be fine here.
Some logs:
2018-10-17 20:05:29.932 INFO 15968 --- [nio-8090-exec-1]
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring
FrameworkServlet 'dispatcherServlet' 2018-10-17 20:05:29.932 INFO
15968 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet :
FrameworkServlet 'dispatcherServlet': initialization started
2018-10-17 20:05:29.938 INFO 15968 --- [nio-8090-exec-1]
o.s.web.servlet.DispatcherServlet : FrameworkServlet
'dispatcherServlet': initialization completed in 6 ms 2018-10-17
20:05:37.694 INFO 15968 --- [nio-8090-exec-3]
o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using
ASTQueryTranslatorFactory 2018-10-17 20:05:37.701 DEBUG 15968 ---
[nio-8090-exec-3] org.hibernate.SQL :
select
userinfo0_.userid as userid1_1_,
userinfo0_.enabled as enabled2_1_,
userinfo0_.password as password3_1_,
userinfo0_.role as role4_1_
from
tuserid userinfo0_
where
userinfo0_.userid=?
and userinfo0_.enabled=? 2018-10-17 20:05:37.701 TRACE 15968 --- [nio-8090-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [kudelam] 2018-10-17 20:05:37.701
TRACE 15968 --- [nio-8090-exec-3] o.h.type.descriptor.sql.BasicBinder
: binding parameter [2] as [SMALLINT] - [1] 2018-10-17 20:05:37.715
ERROR 15968 --- [nio-8090-exec-3]
w.a.UsernamePasswordAuthenticationFilter : An internal error occurred
while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException:
A granted authority textual representation is required
Could you please take a look and shred some light on this?
Try it this way instead of
GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(),
activeUserInfo.getPassword(), Arrays.asList(authority));
Do
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(activeUserInfo.getRole()));
return new org.springframework.security.core.userdetails.User(activeUserInfo.getUsername(),
activeUserInfo.getPassword(),
grantedAuthorities);

Spring Boot application.properties value not populating

I have a very simple Spring Boot app that I'm trying to get working with some externalised configuration. I've tried to follow the information on the spring boot documentation however I'm hitting a road block.
When I run the app below the external configuration in the application.properties file does not get populated into the variable within the bean. I'm sure I'm doing something stupid, thanks for any suggestions.
MyBean.java (located in /src/main/java/foo/bar/)
package foo.bar;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {
System.out.println("================== " + prop + "================== ");
}
}
Application.java (located in /src/main/java/foo/)
package foo;
import foo.bar.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
#Autowired
private MyBean myBean;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties (located in /src/main/resources/)
some.prop=aabbcc
Log output when executing the Spring Boot app:
grb-macbook-pro:properties-test-app grahamrb$ java -jar ./build/libs/properties-test-app-0.1.0.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.1.5.RELEASE)
2014-09-10 21:28:42.149 INFO 16554 --- [ main] foo.Application : Starting Application on grb-macbook-pro.local with PID 16554 (/Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app/build/libs/properties-test-app-0.1.0.jar started by grahamrb in /Users/grahamrb/Dropbox/dev-projects/spring-apps/properties-test-app)
2014-09-10 21:28:42.196 INFO 16554 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:42.828 INFO 16554 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-09-10 21:28:43.592 INFO 16554 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-09-10 21:28:43.784 INFO 16554 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2014-09-10 21:28:43.785 INFO 16554 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.54
2014-09-10 21:28:43.889 INFO 16554 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2014-09-10 21:28:43.889 INFO 16554 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1695 ms
2014-09-10 21:28:44.391 INFO 16554 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-09-10 21:28:44.393 INFO 16554 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
================== null==================
2014-09-10 21:28:44.606 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.679 INFO 16554 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.679 INFO 16554 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-09-10 21:28:44.716 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.716 INFO 16554 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-09-10 21:28:44.902 INFO 16554 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-09-10 21:28:44.963 INFO 16554 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-09-10 21:28:44.965 INFO 16554 --- [ main] foo.Application : Started Application in 3.316 seconds (JVM running for 3.822)
^C2014-09-10 21:28:54.223 INFO 16554 --- [ Thread-2] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e38ec8: startup date [Wed Sep 10 21:28:42 EST 2014]; root of context hierarchy
2014-09-10 21:28:54.225 INFO 16554 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
#Component
public class MyBean {
private final String prop;
#Autowired
public MyBean(#Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
public MyBean() {
}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.
Your current way(#grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.
This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the #Value setting was still not taking effect. And then after doing File > Invalidate Cache / Restart with my IntelliJ (my IDE), the problem went away ...
This is very easy to try so may be worth a shot
Actually, For me below works fine.
#Component
public class MyBean {
public static String prop;
#Value("${some.prop}")
public void setProp(String prop) {
this.prop= prop;
}
public MyBean() {
}
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Now whereever i want, just invoke
MyBean.prop
it will return value.
Moved no argument constructor code to PostConstruct has done the trick
for me. As it'll keep default bean loading workflow intact.
#Component
public class MyBean {
#Value("${some.prop}")
private String prop;
#PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Using Environment class we can get application. Properties values
#Autowired,
private Environment env;
and access using
String password =env.getProperty(your property key);
follow these steps.
1:- create your configuration class like below you can see
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
#Configuration
public class YourConfiguration{
// passing the key which you set in application.properties
#Value("${some.pro}")
private String somePro;
// getting the value from that key which you set in application.properties
#Bean
public String getsomePro() {
return somePro;
}
}
2:- when you have a configuration class then inject in the variable from a configuration where you need.
#Component
public class YourService {
#Autowired
private String getsomePro;
// now you have a value in getsomePro variable automatically.
}
If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.
If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.
This solved the issue for me.
You can use Environment Class to get data :
#Autowired
private Environment env;
String prop= env.getProperty('some.prop');
Simplest solution that solved this issue for me:
Add #PropertySource annotation to the Component/Service that needs to populate #Value field:
#Service
#PropertySource("classpath:myproperties.properties")
public class MyService {
#Value("${some.prop}")
private String someProperty;
// some logic...
}
Make sure to add the properties file to the resource folder of the same module as your Service/Component.
You are getting this error because you are initializing the class with new keyword. To solve this,
first you need to create the configuration class and under this class you need to create the bean of this class.
When you will call it by using bean then it will work..
package ca.testing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
#Component
#PropertySource("db.properties")
public class ConnectionFactory {
#Value("${jdbc.user}")
private String user;
#Value("${jdbc.password}")
private String password;
#Value("${jdbc.url}")
private String url;
Connection connection;
public Connection getConnection(){
try {
connection = DriverManager.getConnection(url, user, password);
System.out.println(connection.hashCode());
}catch (Exception e){
System.out.println(e);
}
return connection;
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(Config.class);
ConnectionFactory connectionFactory= context.getBean(ConnectionFactory.class);
connectionFactory.getConnection();
}
}
My application properties are picking after i have removed key word new from different class like (new Bean())

Categories

Resources