Hello I'm totally new to Spring Framework. I wanted to #Autowired the JdbcTemplate inside MasterDaoImpl but it returns NullPointerException.
I believe #Autowired objects are created after constructor.
It returns an address if i tried to print in one of the Configuration classes. I don't know what to do ? What should i do in order to make the
JdbcTemplate work inside of MasterDaoImpl.
Can anyone explain why this is happening ? Any Suggestions with the Configurations are appreciated.
AppConfig.java
package com.upeg.requisition.config;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.upeg.requisition")
public class AppConfig implements WebMvcConfigurer {
private static final Logger logger = Logger.getLogger(AppConfig.class);
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles.xml", "/WEB-INF/loginTiles.xml" });
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// registry.jsp("/WEB-INF/pages/", ".jsp");
TilesViewResolver tilesViewResolver = new TilesViewResolver();
registry.viewResolver(tilesViewResolver);
}
#Bean("messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("languages/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
}
AppInitialiser.java
package com.upeg.requisition.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SecurityConfig.class,AppConfig.class,DatabaseConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
DatabaseConfig.java
package com.upeg.requisition.config;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#PropertySource(value = { "classpath:application.properties" })
#EnableTransactionManagement
#ComponentScan("com.upeg.requisition")
public class DatabaseConfig {
private static final Logger logger = Logger.getLogger(DatabaseConfig.class);
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
}
SecurityConfig.java
package com.upeg.requisition.config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
#ComponentScan("com.upeg.requisition")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomSuccesHandler customSuccesHandler;
private static final Logger logger = Logger.getLogger(SecurityConfig.class);
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/css/**", "/javascript/**", "/images/**", "/fonts/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login")
.usernameParameter("username").passwordParameter("password").successHandler(customSuccesHandler).and()
.httpBasic().and().logout().invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/login").permitAll().and().csrf().disable();
http.sessionManagement().maximumSessions(1);
http.exceptionHandling().accessDeniedPage("/denied");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user#user.com").password("{noop}Password1234!").roles("USER").and()
.withUser("approver#approver.com").password("{noop}Password1234!").roles("ADMIN");
}
}
MasterTableDao.java
public interface MasterTableDao {
List<MasterCategory> getCategory();
}
MasterDaoImpl.java
package com.upeg.requisition.daoimpl;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.upeg.requisition.config.AppConfig;
import com.upeg.requisition.config.CustomRowMapper;
import com.upeg.requisition.dao.MasterTableDao;
import com.upeg.requisition.model.MasterCategory;
#Repository
public class MasterDaoImpl implements MasterTableDao {
private static final Logger logger = Logger.getLogger(MasterDaoImpl.class);
#Autowired
JdbcTemplate jdbcTemplate;
#Override
public List<MasterCategory> getCategory() {
return jdbcTemplate.query("select * from category",new CustomRowMapper());
}
}
```[enter image description here][1]
[1]: https://i.stack.imgur.com/xTSc4.png
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(datasource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
jdbcTemplate.setDataSource(datasource); can be more appropriate but that's not the answer so you can put DatabaseConfig to AppIntializer
return new Class[]{SecurityConfig.class,AppConfig.class, DatabaseConfig.class};
I guess ComponentScan didn't work.
I just made these changes and it worked just gave my Bean a name and worked :)
#Bean("dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl(" jdbc:postgresql://localhost:5432/test");
dataSource.setUsername("postgres");
dataSource.setPassword("sillicon");
return dataSource;
}
#Bean("jdbcTemplate")
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
Related
Recently in my project I was asked to use Spring's #Cacheable annotation for one of the method which returns static referenceData from the database. I followed this blog https://medium.com/#d.lopez.j/configuring-multiple-ttl-caches-in-spring-boot-dinamically-75f4aa6809f3 which guides to have caches created dynamically. I am trying to test this implementation by following this SO answer How to test Spring's declarative caching support on Spring Data repositories? and I am facing issues. I am not able to load the properties from the application-test.properties into my test class.
My CachingConfig Class
package org.vinodh.testing;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Data;
#Configuration
#ConfigurationProperties(prefix = "caching")
#Data
public class CachingConfig {
private Map<String, CacheSpec> specs;
#Data
public static class CacheSpec {
private int minutesToExpire;
private int maximumSize;
public int getMaximumSize() {
return maximumSize;
}
public void setMaximumSize(int maximumSize) {
this.maximumSize = maximumSize;
}
public int getMinutesToExpire() {
return minutesToExpire;
}
public void setMinutesToExpire(int minutesToExpire) {
this.minutesToExpire = minutesToExpire;
}
}
public Map<String, CacheSpec> getSpecs() {
return specs;
}
#Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
if (specs != null) {
List<CaffeineCache> caches = specs.entrySet().stream()
.map(entry -> buildCache(entry.getKey(), entry.getValue())).collect(Collectors.toList());
cacheManager.setCaches(caches);
}
return cacheManager;
}
private CaffeineCache buildCache(String name, CacheSpec specs) {
Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder()
.expireAfterWrite(specs.getMinutesToExpire(), TimeUnit.MINUTES).maximumSize(specs.getMaximumSize());
return new CaffeineCache(name, caffeineBuilder.build());
}
}
My Test Class
package org.vinodh.testing;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
#ConfigurationProperties(prefix = "caching")
#ActiveProfiles("test")
#Profile("test")
public class CachingConfigTest {
#Configuration
#EnableCaching
static class NestedCacheConfiguration {
static class CacheSpec {
#SuppressWarnings("unused")
private int minutesToExpire;
#SuppressWarnings("unused")
private int maximumSize;
}
private Map<String, CacheSpec> specs;
public Map<String, CacheSpec> getSpecs() {
return specs;
}
#Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
System.out.println(getSpecs()); // Is null
return cacheManager;
}
}
#Test
public void test() {
System.out.println("Inside Test");
}
}
application-test.properties
caching.specs.test.minutesToExpire=10
caching.specs.test.maximumSize=10
I have configured Spring and Hibernate for Mysql but hibernate is not creating tables automatically.i have configured mysql in eclipse datasource connection and tried with tomcat 8 and tomcat 9
I have Configured Database properties to configure hibernate
please find the code below
Database.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/bookdb
mysql.user=root
mysql.password=root
# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
AppConfig
package com.bushansirgur.config;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.hibernate.cfg.Environment.*;
#Configuration
#PropertySource("classpath:db.properties")
#EnableTransactionManagement
#ComponentScans(value = { #ComponentScan("com.bushansirgur.dao"),
#ComponentScan("com.bushansirgur.service") })
public class AppConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
Properties props = new Properties();
// Setting JDBC properties
props.put(DRIVER, env.getProperty("mysql.driver"));
props.put(URL, env.getProperty("mysql.url"));
props.put(USER, env.getProperty("mysql.user"));
props.put(PASS, env.getProperty("mysql.password"));
// Setting Hibernate properties
props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
// Setting C3P0 properties
props.put(C3P0_MIN_SIZE, env.getProperty("hibernate.c3p0.min_size"));
props.put(C3P0_MAX_SIZE, env.getProperty("hibernate.c3p0.max_size"));
props.put(C3P0_ACQUIRE_INCREMENT,
env.getProperty("hibernate.c3p0.acquire_increment"));
props.put(C3P0_TIMEOUT, env.getProperty("hibernate.c3p0.timeout"));
props.put(C3P0_MAX_STATEMENTS, env.getProperty("hibernate.c3p0.max_statements"));
factoryBean.setHibernateProperties(props);
factoryBean.setPackagesToScan("com.bushansirgur.model");
return factoryBean;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
}
MyWebAppIntitalizer
package com.bushansirgur.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebConfig
package com.bushansirgur.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.bushansirgur.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
}
BookModel.java
package com.bushansirgur.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name = "Book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
The problem is AppConfig class is in package com.bushansirgur.config which is not under the#ComponentScan, and also i do see multiple #ComponentScan annotations on different class which is not recommended. You can simply use it once on Main class with base package
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.bushansirgur" })
public class WebConfig extends WebMvcConfigurerAdapter {
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
package com.phynart.cloud.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfig.class);
static final String CLIEN_ID = "devglan-client";
static final String CLIENT_SECRET = "devglan-secret";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
#Autowired
private AuthenticationManager authenticationManager;
#Bean
public JwtAccessTokenConverter accessTokenConverter() {
logger.debug("in access token converter");
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("as466gf");
return converter;
}
#Bean
public TokenStore tokenStore() {
logger.debug("tokenStore");
return new JwtTokenStore(accessTokenConverter());
}
#Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
logger.debug("ClientDetailsServiceConfigurer");
configurer
.inMemory()
.withClient(CLIEN_ID)
.secret(CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
logger.debug("AuthorizationServerEndpointsConfigurer");
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
}
package com.phynart.cloud.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);
private static final String RESOURCE_ID = "resource_id";
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
logger.debug("ResourceServerSecurityConfigurer");
resources.resourceId(RESOURCE_ID).stateless(false);
}
#Override
public void configure(HttpSecurity http) throws Exception {
logger.debug("HttpSecurity resource");
http.
anonymous().disable()
.authorizeRequests()
.antMatchers("/users/**").access("hasRole('ADMIN')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
package com.phynart.cloud.config;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
#Resource(name = "UserService")
private UserDetailsService userDetailsService;
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
logger.debug("inside authentication manager");
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
logger.debug("password encoder");
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
logger.debug("HttpSecurity");
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api-docs/**").permitAll();
}
#Bean
public BCryptPasswordEncoder encoder(){
logger.debug("inside password encoder");
// return new BCryptPasswordEncoder();
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
logger.debug("bCryptPasswordEncoder -" + bCryptPasswordEncoder);
return bCryptPasswordEncoder;
}
#Bean
public FilterRegistrationBean corsFilter() {
logger.debug("corsFilter");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
package com.phynart.cloud.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.phynart.cloud.model.User;
import com.phynart.cloud.service.UserService;
import java.security.Principal;
#RestController
#RequestMapping("/users")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#RequestMapping(value="/user", method = RequestMethod.GET)
public Iterable<User> listUser(){
logger.debug("inside controller");
return userService.findAll();
}
#RequestMapping(value = "/user", method = RequestMethod.POST)
public User create(#RequestBody User user){
return userService.save(user);
}
#RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public String delete(#PathVariable(value = "id") Long id){
userService.delete(id);
return "success";
}
}
package com.phynart.cloud.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.phynart.cloud.dao.UserDao;
import com.phynart.cloud.model.User;
#Service(value = "UserService")
public class UserServiceImpl implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
#Autowired
private UserDao userDao;
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
logger.debug("loadUserByUsername");
User user = userDao.findByUsername(userId);
if(user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
logger.debug("before returning user");
logger.debug("username -" + user.getUsername());
logger.debug("password -" + user.getPassword());
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority());
}
private List getAuthority() {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
public List findAll() {
logger.debug("findAll");
List list = new ArrayList<>();
userDao.findAll().iterator().forEachRemaining(list::add);
return list;
}
}
package com.phynart.cloud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import com.phynart.cloud.dao.UserDao;
import com.phynart.cloud.model.User;
#Service
public class UserService {
#Autowired
UserDao userDao;
public Iterable<User> findAll() {
return userDao.findAll();
}
public User save(User user) {
return userDao.save(user);
}
public void delete(Long id) {
// TODO Auto-generated method stub
}
}
I am getting bad credentials "Handling error: InvalidGrantException, Bad credentials", even If i comment the BCryptPasswordEncoder portion and use plain password in database still am facing issue, could anyone please help me out? i am not finding any solution and I am new to oauth implementation,
i have added the AuthorizartionServerConfig, ResourceServerConfig, SecurityConfig, UserServiceImpl, UserController - I have pulled the code from site - https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example
basic auth from postman
Body in postman for user credetial
database credential of the user
data entered from the site i coded - https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example
I think you have a typo in parameters for user credentials.
body in postman for user credentials
passowrd
instead of
password
I need some help.
Spring doesn't seem to recognize my methods which was annotated with #Transactional. I watched a lot of sources for solution but couldn't find one.
And I need to annotate exactly dao methods, not services(I know that this is best practice).
P.S. Sorry for my bad english.
My appInitializer:
package com.dreamteam.datavisualizator.common.configurations;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{ServletContext.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{ApplicationContext.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
My servletContext:
package com.dreamteam.datavisualizator.common.configurations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#ComponentScan(basePackages = "com.dreamteam.datavisualizator")
#EnableWebMvc
#EnableTransactionManagement
public class ServletContext extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
My applicationContext:
package com.dreamteam.datavisualizator.common.configurations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
#Configuration
public class ApplicationContext {
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl(System.getenv("SQL_JDBC_URL"));
dataSource.setUsername(System.getenv("SQL_LOGIN"));
dataSource.setPassword(System.getenv("SQL_PASSWORD"));
return dataSource;
}
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(getDataSource());
}
#Bean(name="generalTemplate")
public JdbcTemplate getJdbcTemplate(){
return new JdbcTemplate(getDataSource());
}
#Bean(name="simpleCallTemplate")
public SimpleJdbcCall getSimpleJdbcCall(){
return new SimpleJdbcCall(getDataSource());
}
}
My Dao class (in this method can be more calls of SimpleJdbcCall/ but that for example):
#Repository("userDaoImpl")
public class UserDAOImpl implements UserDAO {
private enum UserColumnName {ID, FIRST_NAME, LAST_NAME, EMAIL}
#Autowired
private JdbcTemplate generalTemplate;
#Autowired
private SimpleJdbcCall simpleCallTemplate;
//...
#Transactional
public BigInteger createObject(BigInteger object_id, String name) {
simpleCallTemplate.withFunctionName(INSERT_OBJECT);
SqlParameterSource in = new MapSqlParameterSource()
.addValue("obj_type_id", object_id)
.addValue("obj_name", name);
return simpleCallTemplate.executeFunction(BigDecimal.class, in).toBigInteger();
}
//...
private String INSERT_OBJECT = "insert_object";
}
Your configuration seems to be correct. I believe it's not working because you did not specify rollbackFor
#Transactional(value = "transactionManager", rollbackFor = java.lang.Exception.class)
public BigInteger createObject(BigInteger object_id, String name) {
simpleCallTemplate.withFunctionName(INSERT_OBJECT);
SqlParameterSource in = new MapSqlParameterSource()
.addValue("obj_type_id", object_id)
.addValue("obj_name", name);
return simpleCallTemplate.executeFunction(BigDecimal.class, in).toBigInteger();
}
Now if an exception of type java.lang.Exception occurs in your method, it'll rollback all changes
Maybe it is because of Open Session?
https://vladmihalcea.com/the-open-session-in-view-anti-pattern/
Try that in the properties file:
spring.jpa.open-in-view=false
I wrote a DAL following this guide. In particular this is my DALConfig.java configuration file
package my.pack;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.hibernate.ejb.HibernatePersistence;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.Repository;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan(basePackages = { "my.pack" })
#PropertySource("classpath:dbconnection.properties")
#EnableJpaRepositories("my.pack.repository")
#EnableTransactionManagement
public class DALConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver_class";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_POOL_INITIAL_SIZE = "pool.initialsize";
private static final String PROPERTY_NAME_POOL_MAX_IDLE = "pool.maxidle";
private static final String PROPERTY_NAME_DAL_CLASSES_PACKAGE = "entities.packages_to_scan";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.showsql";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
#Resource
private Environment environment;
#Bean
public DataSource dataSource()
{
Properties props = new Properties();
props.put("driverClassName", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
props.put("url", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
props.put("username", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
props.put("password", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
props.put("initialSize", environment.getRequiredProperty(PROPERTY_NAME_POOL_INITIAL_SIZE));
props.put("maxIdle", environment.getRequiredProperty(PROPERTY_NAME_POOL_MAX_IDLE));
BasicDataSource bds = null;
try {
bds = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bds;
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor()
{
PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor();
return b;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Bean
public PlatformTransactionManager transactionManager() throws ClassNotFoundException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_DAL_CLASSES_PACKAGE));
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties jpaProterties = new Properties();
jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
entityManagerFactoryBean.setJpaProperties(jpaProterties);
return entityManagerFactoryBean;
}
}
This is the Repository I wrote
package my.pack.repository;
import my.pack.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface IUserRepository extends CrudRepository<User, String>{
}
Finally this is the test I run
package my.pack.tests;
import static org.junit.Assert.assertTrue;
import futureservice.UserService;
import my.pack.DALConfig;
import my.pack.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#ContextConfiguration(classes = { DALConfig.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class DALTest {
#Autowired
UserService userService;
#Test
public void testGetUser() {
User user = null;
user = userService.findOne("mrossi");
assertTrue(null != user);
}
}
When I run the test I get the following exception stack and the test fails.
...
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'entityManager' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.setMappingContext(Lorg/springframework/data/mapping/context/MappingContext;)V
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:108)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:62)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1489)
... 41 more
It seems like the JpaRepositoryFactoryBean misses the setMappingContext method but as you can see from the documentation the method is supported. I'm using the 1.5.1.RELEASE version of spring-data-jpa artifact.
What can be the issue?
Thank you