Configuring Apache Shiro 1.7.0 with Springboot 2.4.0 - spring-boot

I'm trying to add Apache shiro 1.7.0 as security manager bellow you will find my configuration class :
public class ShiroConfig {
#Bean(name="shiroFilter")
#DependsOn({"securityManager"})
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
log.info("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/captcha", "anon");
filterChainDefinitionMap.put("/app/code/**", "anon");
filterChainDefinitionMap.put("admin/**/page-query", "user");
filterChainDefinitionMap.put("/app/web/logout", "logout");
filterChainDefinitionMap.put("admin/**/detail", "authc");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
#Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();
return lifecycleBeanPostProcessor;
}
#Bean(name="ehCacheManager")
#DependsOn("lifecycleBeanPostProcessor")
public EhCacheManager ehCacheManager() {
log.info("ShiroConfiguration.getEhCacheManager()");
EhCacheManager cacheManager = new EhCacheManager();
cacheManager.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return cacheManager;
}
#Bean(name="adminRealm")
#DependsOn("lifecycleBeanPostProcessor")
public AdminRealm adminRealm(EhCacheManager ehCacheManager) {
AdminRealm adminRealm = new AdminRealm() ;
adminRealm.setCacheManager(ehCacheManager);
return adminRealm;
}
#Bean(name="simpleCookie")
public SimpleCookie getSimpleCookie(){
SimpleCookie simpleCookie = new SimpleCookie();
simpleCookie.setName("rememberMe");
simpleCookie.setHttpOnly(true);
simpleCookie.setMaxAge(7*24*60*60);
return simpleCookie ;
}
#Bean(name="cookieRememberMeManager")
#DependsOn({"simpleCookie"})
public CookieRememberMeManager getCookieRememberMeManager(SimpleCookie simpleCookie){
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(simpleCookie);
cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
return cookieRememberMeManager ;
}
#Bean(name = "securityManager")
#DependsOn({"adminRealm","ehCacheManager","cookieRememberMeManager"})
public DefaultWebSecurityManager getDefaultWebSecurityManager(AdminRealm realm, EhCacheManager ehCacheManager,CookieRememberMeManager cookieRememberMeManager) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
defaultWebSecurityManager.setCacheManager(ehCacheManager);
defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);
return defaultWebSecurityManager;
}
#Bean
#DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
#Bean
#DependsOn("securityManager")
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
my pom.xml entry for shiro :
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.7.0</version>
</dependency>
The project compile successfully but i'm getting the above error while trying to access the web app, i appreciate any hemp or suggestion.
Error starting Tomcat context. Exception:
org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'filterShiroFilterRegistrationBean' defined in class path resource [org/apache/shiro/spring/config/web/autoconfigure/ShiroWebFilterConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.FilterRegistrationBean]: Factory method 'filterShiroFilterRegistrationBean' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'shiroFilterFactoryBean' available

Try adding #Configuration annotations to the class,like this:

try changing the name of your bean from #Bean(name="shiroFilter") to #Bean(name="shiroFilterFactoryBean").

Related

Springboot with Redis Sentinals getting UnsatisfiedDependencyException

I am not able to connect with Redis Sentinal nodes using Spring boot. I am getting UnsatisfiedDependencyException while creating bean cacheManager and localCacheManager. I am not getting where I am doing wrong. Can anyone please help me out.
Using Spring boot version - 2.6. Maven dependencies are -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.6</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.2</version>
<optional>true</optional>
</dependency>
Code -
#EnableAutoConfiguration
#Configuration
#EnableCaching
public class RedisCacheConfig {
private final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
#Value("${spring.profiles.active}")
private String profiles;
#Value("${redis.sentinel.nodes}")
private String sentinelNodes;
#Value("${redis.sentinel.password}")
private String redisPassword;
#Value("${redis.sentinel.master.name}")
private String redisMasterName;
#Value("${redis.sentinel.master.node}")
private String redisMasterNode;
#Value("${redis.sentinel.port}")
private Integer redisSentinelPort;
#Value("${redis.port}")
private Integer redisPort;
#Value("${pool.max.wait.seconds}")
public int secondsToWait;
#Value("${pool.max.total}")
public int maxTotal;
#Value("${pool.max.idle}")
public int maxIdle;
#Value("${pool.min.idle}")
public int minIdle;
public String cacheNames;
#Bean
public CacheManager cacheManager(RedisTemplate<String, String> redisTemplate) {
if(!StringUtils.hasLength(profiles)) {
if(profiles.toLowerCase().contains("dev")) {
cacheNames = ":DEV:";
} else if(profiles.toLowerCase().contains("qa")) {
cacheNames = ":PROD:";
}
}
RedisCacheManager.builder(connectionFactory())
.cacheDefaults(RedisCacheConfiguration
.defaultCacheConfig().prefixCacheNameWith(cacheNames)).build();
return cacheManager(redisTemplate);
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory factory = null;
try {
long seconds=secondsToWait * 1000L;
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setMaxWaitMillis(seconds);
factory = new JedisConnectionFactory(sentinelConfig(), poolConfig);
factory.setUsePool(true);
factory.setPassword(redisPassword);
factory.setPort(redisPort);
factory.afterPropertiesSet();
} catch(Exception e) {
e.printStackTrace();
}
return factory;
}
#Bean
public RedisSentinelConfiguration sentinelConfig() {
String[] nodes = StringUtils.commaDelimitedListToStringArray(sentinelNodes);
logger.info("===================== Connecting to Redis 3 =====================");
logger.info(Arrays.toString(nodes));
final RedisSentinelConfiguration SENTINEL_CONFIG = new RedisSentinelConfiguration().master(redisMasterName).sentinel(redisMasterNode, redisSentinelPort);
SENTINEL_CONFIG.setPassword(redisPassword);
for (String node : nodes) {
SENTINEL_CONFIG.sentinel(node, redisSentinelPort);
}
return SENTINEL_CONFIG;
}
}
Code (RedisTemplate) -
#Bean
public RedisTemplate<Object, Object> redisTemplate(JedisConnectionFactory cf) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(cf);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setKeySerializer(new GenericToStringSerializer<Long>(Long.class));
return redisTemplate;
}
Error code I am getting below -
cancelling refresh attempt: creating bean with name
'localCacheManager': Unsatisfied dependency expressed through field
'redisCacheManager';
nested exception Error creating bean with name 'cacheManager' defined
in class path resource [com/RedisCacheConfig.class]:
nested exception Error creating bean with name 'stringRedisTemplate'
defined in class path resource
[org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]:
Unsatisfied dependency expressed through method 'stringRedisTemplate'
parameter 0;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'connectionFactory' defined in class path
resource [com/abc/mbile/xyz/RedisCacheConfig.class]: Bean
instantiation via factory method failed;
nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.redis.connection.jedis.JedisConnectionFactory]:
Factory method 'connectionFactory' threw exception;
nested exception is java.lang.NoClassDefFoundError:
redis/clients/jedis/GeoUnit
You are trying to use Jedis 4.x with Spring boot 2.x.
It could be a difficult job to use Jedis 4.x with Spring boot 2.x.
There are some users who are using Jedis 4 but this is possible IFF you are not using some certain features and are willing to go through some extra works.
Until Spring releases support for Jedis 4, you may consider sticking to Jedis 3.x.

the value is not loaded via Injection

There is a problem. I launch the application and an error appears: Error creating bean with name 'kafkaConsumerConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.kafka.bootstrap-servers' in value "${spring.kafka.bootstrap-servers}" Tell me what to do?
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public SpringLiquibase liquibase(DataSource ds) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setChangeLog("classpath:liquibase-changeLog.xml");
liquibase.setDataSource(ds);
return liquibase;
}
}
#Configuration
public class KafkaConsumerConfig {
#Value("${spring.kafka.bootstrap-servers}")
private String kafkaServer;
#Value("${spring.kafka.consumer.group-id}")
private String kafkaGroupId;
#Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaGroupId);
props.put(JsonDeserializer.TRUSTED_PACKAGES, "ru.job4j");
return props;
}
#Bean
public KafkaListenerContainerFactory<?> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, Passport> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
#Bean
public ConsumerFactory<Integer, Passport> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
}
file application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost:5432/managing
spring.datasource.username=pos
spring.datasource.password=pas
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
api-url=http://localhost:8080/api
spring.kafka.consumer.group-id=app.1
spring.kafka.bootstrap-servers=localhost:9092
server.port=8084
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Couldn't determine Dialect for "oracle"

I am using Spring boot(2.3.5), Oracle19c DB, and Hibernate(5.4).
I tried to make multi-datasource connection, but I keep getting a dialect error Couldn't determine Dialect for "oracle".
Error creating bean with name 'jdbcDialect' defined in class path resource [org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfiguration$SpringBootJdbcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.relational.core.dialect.Dialect]: Factory method 'jdbcDialect' threw exception; nested exception is org.springframework.data.jdbc.repository.config.DialectResolver$NoDialectException: Cannot determine a dialect for org.springframework.jdbc.core.JdbcTemplate#2ba9ed19. Please provide a Dialect.
I basically followed this tutorial to configure multiple data sources.
application.properties:
spring.datasource-primary.username=oracleprimary
spring.datasource-primary.password=oracleprimary
spring.datasource-primary.url=jdbc:oracle:thin:#//localhost:1521/orcl
spring.datasource-secondary.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource-secondary.username=oraclesecondary
spring.datasource-secondary.password=oraclesecondary
spring.datasource-secondary.url=jdbc:oracle:thin:#//localhost:1521/orcl
Primary configuration:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager",
basePackages = {"com.foo.primary.repository"})
public class PrimaryDataSourceConfiguration {
#Primary
#Bean(name = "primaryDataSourceProperties")
#ConfigurationProperties("spring.datasource-primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
#Primary
#Bean(name = "primaryDataSource")
#ConfigurationProperties("spring.datasource-primary.configuration")
public DataSource primaryDataSource(#Qualifier("primaryDataSourceProperties") DataSourceProperties primaryDataSourceProperties) {
return primaryDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
#Primary
#Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
EntityManagerFactoryBuilder primaryEntityManagerFactoryBuilder, #Qualifier("primaryDataSource") DataSource primaryDataSource) {
Map<String, String> primaryJpaProperties = new HashMap<>();
primaryJpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle12cDialect");
return primaryEntityManagerFactoryBuilder
.dataSource(primaryDataSource)
.packages("com.foo.primary.model")
.persistenceUnit("primaryDataSource")
.properties(primaryJpaProperties)
.build();
}
#Primary
#Bean(name = "primaryTransactionManager")
public PlatformTransactionManager primaryTransactionManager(
#Qualifier("primaryEntityManagerFactory") EntityManagerFactory primaryEntityManagerFactory) {
return new JpaTransactionManager(primaryEntityManagerFactory);
}
Second configuration:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "secondaryEntityManagerFactory",
transactionManagerRef = "secondaryTransactionManager",
basePackages = {"com.foo.secondary.repository"})
public class SecondaryDataSourceConfiguration {
#Bean(name = "secondaryDataSourceProperties")
#ConfigurationProperties("spring.datasource-secondary")
public DataSourceProperties secondaryDataSourceProperties() {
return new DataSourceProperties();
}
#Bean(name = "secondaryDataSource")
#ConfigurationProperties("spring.datasource-secondary.configuration")
public DataSource secondaryDataSource(#Qualifier("secondaryDataSourceProperties") DataSourceProperties secondaryDataSourceProperties) {
return secondaryDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
#Bean(name = "secondaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
EntityManagerFactoryBuilder secondaryEntityManagerFactoryBuilder, #Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
Map<String, String> secondaryJpaProperties = new HashMap<>();
secondaryJpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle12cDialect");
return secondaryEntityManagerFactoryBuilder
.dataSource(secondaryDataSource)
.packages("com.foo.secondary.model")
.persistenceUnit("secondaryDataSource")
.properties(secondaryJpaProperties)
.build();
}
#Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager(
#Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {
return new JpaTransactionManager(secondaryEntityManagerFactory);
}
}
I also tried org.hibernate.dialect.Oracle10gDialect, and set spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect in application.properties, but nothing changed.
How can I properly configure dialect for oracle?
Spring Data JDBC does not support oracle dialect. You need to define your dialect that implements JdbcDialectProvider.
public final class OracleDialect implements DialectResolver.JdbcDialectProvider {
private static Dialect getDialect(Connection connection) throws SQLException {
DatabaseMetaData metaData = connection.getMetaData();
String name = metaData.getDatabaseProductName().toLowerCase(Locale.ROOT);
if (name.contains("oracle")) {
return AnsiDialect.INSTANCE;
}
return null;
}
#Override
public Optional<Dialect> getDialect(JdbcOperations operations) {
return Optional.ofNullable(operations.execute((ConnectionCallback<Dialect>) OracleDialect::getDialect));
}
}
Add spring-boot-starter-data-jdbc dependency in your build.gradle or pom.xml.
Then, as mentioned in the blog, create spring.factories file in resources/META-INF, and paste the following command:
org.springframework.data.jdbc.repository.config.DialectResolver$JdbcDialectProvider=<your-package>.OracleDialect
Also, since both databases you use are the same (OracleDB), you do not need to set .properties() for entity manager. As #SternK mentioned, you can have spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect in your application.properties only.

NullPointerException in RedisCache class (line number 614). Version 1.8.22

Sometimes NullPointerException occurs in RedisCache class (line number 614). Version 1.8.22
Spring Boot version: 1.5.21.RELEASE
Redis Configuration:
#Bean(name = "stringJdkTransactionalRedisTemplate")
public RedisTemplate getRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
#Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
#Bean
public LettuceConnectionFactory connectionFactory() {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
connectionFactory.setHostName(redisHost);
connectionFactory.setPort(redisPort);
connectionFactory.setPassword(redisPassword);
return connectionFactory;
}
The execution code
public void method1() {
SecurityContext securityContext = SecurityContextHolder.getContext();
User contextUser = ((CustomUser)securityContext.getAuthentication().getPrincipal()).getCustomUser();
contextUser.setRegistrationStatus(clientRegistrationStatus);
redisTemplate.opsForHash().put("spring:session:sessions:" + sessionId, "sessionAttr:SPRING_SECURITY_CONTEXT", securityContext);
method2(user);
}
#Transactional
#CacheEvict(value = CacheName.USER_CACHE, key = "'getByEmail.' + #user.email")
public User methood2(#NotNull User user) {
return userRepository.saveAndFlush(user);
}
SOMETIMES this code throws following exception on the last line of the method1
java.lang.NullPointerException: nulljava.lang.NullPointerException: null at
org.springframework.data.redis.cache.RedisCache$AbstractRedisCacheCallback.waitForLock(RedisCache.java:614) at
org.springframework.data.redis.cache.RedisCache$AbstractRedisCacheCallback.doInRedis(RedisCache.java:577) at
org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207) at
org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169) at
org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:157) at
org.springframework.data.redis.cache.RedisCache.evict(RedisCache.java:280) at
org.springframework.data.redis.cache.RedisCache.evict(RedisCache.java:269) at org.springframework.cache.interceptor.AbstractCacheInvoker.doEvict(AbstractCacheInvoker.java:98) at
org.springframework.cache.interceptor.CacheAspectSupport.performCacheEvict(CacheAspectSupport.java:476) at
org.springframework.cache.interceptor.CacheAspectSupport.processCacheEvicts(CacheAspectSupport.java:459) at
org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:417) at
org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:323) at
org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61) at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671) at
UserServiceImpl$$EnhancerBySpringCGLIB$$7d5a15d5.method2(<generated>) at
ClientServiceImpl.method1(ClientServiceImpl.java:248)
Indeed, the problem was in the "Transactional" flow.
You have two options here: remove "redisTemplate.setEnableTransactionSupport(true)" from bean configuration or move the method2() out from any Transactional scope.

UnsatisfiedDependencyException: Error creating bean with name

i'm trying to create db server on Spring, and looked through a lot of similar questions, but no one answer to them can't help me. I can't solve this Error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupController': Unsatisfied dependency expressed through field 'gs'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupServiceImpl': Unsatisfied dependency expressed through field 'gr'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepository': Cannot create inner bean '(inner bean)#1a3c15e0' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1a3c15e0': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
So here's my classes :
GroupController.java
#RestController
public class GroupController {
#Autowired
private GroupService gs;
#RequestMapping(value = "/groups", method = RequestMethod.GET)
#ResponseBody
public List<Group> getAllGroups(){
// return mocklist();
return gs.getAll();
}
private List<Group> mocklist() {
Group g= new Group();
g.setId(1);
g.setGroupName("333");
g.setTutorName("shcefsa");
List<Group> list = new ArrayList<Group>();
list.add(g);
g.setId(2);
g.setGroupName("333");
g.setTutorName("shc321efsa");
list.add(g);
return list;
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.GET)
#ResponseBody
public Group getGroupById(#PathVariable("id") int groupId){
return gs.getById(groupId);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group addGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group updateGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.POST)
#ResponseBody
public void deleteGroup(#PathVariable("id") int groupId){
gs.deleteById(groupId);
}
}
GroupRepository.java
#Repository
public interface GroupRepository extends JpaRepository<Group, Integer> {
}
GroupService.java
#Service
public interface GroupService {
List<Group> getAll();
Group getById(int id);
Group add(Group group);
void deleteById(int id);
}
GroupServiceImpl.java`
#Service
public class GroupServiceImpl implements GroupService {
#Autowired
private GroupRepository gr;
public List<Group> getAll() {
return gr.findAll();
}
public Group getById(int id) {
return gr.findOne(id);
}
public Group add(Group group) {
return gr.save(group);
}
public void deleteById(int id) {
gr.delete(id);
}
Looking at other answers, it seems that everything is fine, but it's obvious that there's an error. Hope you'll help me
UPDATE
Databaseconfig.java
#Configuration
#EnableJpaRepositories("com.homestudio.tutor.server.repository")
#EnableTransactionManagement
#PropertySource("classpath:db.properties")
#ComponentScan("com.homestudio.tutor.server")
public class DatabaseConfig {
#Resource
private Environment env;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(getHibernateProperties());
return em;
}
#Bean
public PlatformTransactionManager platformTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return manager;
}
#Bean
public DataSource dataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setUrl(env.getRequiredProperty("db.url"));
ds.setDriverClassName(env.getRequiredProperty("db.driver"));
ds.setUsername(env.getRequiredProperty("db.username"));
ds.setPassword(env.getRequiredProperty("db.password"));
ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMilles")));
ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMilles")));
ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
return ds;
}
public Properties getHibernateProperties() {
try {
Properties properties = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("hibernate.properties");
properties.load(is);
return properties;
} catch (IOException e) {
throw new IllegalArgumentException("Cannot find file \"hibernate.properties\" in classpath");
}
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan("com.homestudio.tutor.server")
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
converters.add(converter);
}
}

Resources