Use of Transactional annotation in Spring data with Hibernate - java

I'm using Spring data and Hibernate to manage my database. I have for example repository class like this:
public interface NotificationHasUserRepository extends JpaRepository<NotificationHasUser, NotificationHasUserKeys> {
List<NotificationHasUser> findByPkUserAndIsReadFalse(User user);
#Modifying
#Query("UPDATE NotificationHasUser u SET u.isRead=true WHERE u.pk.user = ?1")
void setNotificationsAsRead(User user);
void deleteByPkUserAndPkNotification(User user, Notification notification);
List<NotificationHasUser> findByPkUser(User user);
#Query("select count(u)>0 from NotificationHasUser u WHERE u.pk.notification = ?1")
boolean existsByPkNotification(Notification notification);
}
I inject this class in my service class:
#Service
#Transactional
public class NotificationHasUserServicesImpl implements NotificationHasUserServices {
#Resource
private NotificationHasUserRepository notificationHasUserRepository;
#Override
public NotificationHasUser create(NotificationHasUser notificationHasUser) {
return notificationHasUserRepository.save(notificationHasUser);
}
#Override
public NotificationHasUser findById(NotificationHasUserKeys id) {
return notificationHasUserRepository.findOne(id);
}
#Override
public boolean exists(NotificationHasUserKeys id) {
return notificationHasUserRepository.exists(id);
}
#Override
public List<NotificationHasUser> findByPkUserAndIsReadFalse(User user) {
return notificationHasUserRepository.findByPkUserAndIsReadFalse(user);
}
#Override
public void setNotificationsAsRead(User user) {
notificationHasUserRepository.setNotificationsAsRead(user);
}
#Override
public List<NotificationHasUser> getNotifications(User user) {
return notificationHasUserRepository.findByPkUser(user);
}
#Override
public void deleteSelectedNotification(User user, Notification notification) {
notificationHasUserRepository.deleteByPkUserAndPkNotification(user, notification);
}
#Override
public boolean existsByPkNotification(Notification notification) {
return notificationHasUserRepository.existsByPkNotification(notification);
}
}
I'm using #Transaction on the service class but I receive exception when I call delete or update query
.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
If I add #Transcational on each method in repository class all work fine, is it not possible to add at service level?Thanks
This is my spring configuration:
#EnableAsync
#EnableWebMvc
#Configuration
#PropertySource(value = { "classpath:application.properties" })
#ComponentScan({ "com.*" })
#EnableTransactionManagement
#Import({ SecurityConfig.class, SpringMvcInitializer.class})
#EnableJpaRepositories("com.repository")
public class AppConfig extends WebMvcConfigurerAdapter implements AsyncConfigurer{
#Autowired
private Environment env;
#Autowired
private MyAsyncUncaughtExceptionHandler myAsyncUncaughtExceptionHandler;
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
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_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
/**
* This and the next methods are used to avoid exception while jackson mapping the entity, so fields are setted with null value
* unless use Hibernate.initialize
* #return
*/
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
//Registering Hibernate4Module to support lazy objects
mapper.registerModule(new Hibernate4Module());
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
/**
* Used for spring security
* #return
*/
#Bean
public SpringSecurityDialect springSecurityDialect() {
SpringSecurityDialect dialect = new SpringSecurityDialect();
return dialect;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//Here we add our custom-configured HttpMessageConverter
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
properties.put("hibernate.enable_lazy_load_no_trans",true);
return properties;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
ds.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
ds.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
ds.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return ds;
}
#Bean
public ServletContextTemplateResolver TemplateResolver(){
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/templates/pages/");
resolver.setSuffix(".html");
resolver.setTemplateMode("LEGACYHTML5");
resolver.setCacheable(false);
return resolver;
/*ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
return resolver;*/
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(TemplateResolver());
templateEngine.addDialect(springSecurityDialect());
return templateEngine;
}
#Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
resolver.setViewNames(new String[]{"*", "js/*", "template/*"});
return resolver;
}
/**
* Register multipartResolver for file upload
* #return
*/
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
/**
* Allow use of bootstrap
*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
/**
* Allow use of JPA
*/
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(env.
getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
return entityManagerFactoryBean;
}
/**
* Async exception configuration
*/
#Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(10);
executor.initialize();
return executor;
}
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return myAsyncUncaughtExceptionHandler;
}
}

Related

Configuration Spring MVC without web.xml

I'm trying to send requests to my RestController, but it's not working, i have
#RestController
#RequestMapping(
value = "/cursos",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public class CursoRestController {
#Autowired
private CursoService cursoService;
#GetMapping
#ResponseStatus(HttpStatus.OK)
public List<Curso> listAll() {
System.out.println("Test");
return cursoService.findAll();
}
#PostMapping
public ResponseEntity<Void> save(#RequestBody Curso curso) {
cursoService.save(curso);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(curso.getId()).toUri();
return ResponseEntity.created(location).build();
}
I'm using Postman to send request, and when i send some request i get 400 error code, with no message or something to tell to me, what's happing, BUT when i try to open the same URL on the browser, I GET THE RESPONSE, i don't if i configured something wrong, i'm using theses classes to config my project
SpringRootConfig
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("br.com.gabriel.restful")
public class SpringRootConfig {
}
SpringInitConfig
public class SpringInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringRootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
SpringJpaConfig
#Configuration
public class SpringJpaConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost:5432/wildbuild");
ds.setUsername("postgres");
ds.setPassword("admin");
return ds;
}
#Bean
public EntityManagerFactory entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setPackagesToScan("br.com.gabriel.restful.domain");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(jpaProperties());
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public JpaTransactionManager jpaTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
manager.setJpaDialect(new HibernateJpaDialect());
return manager;
}
private Properties jpaProperties(){
Properties props = new Properties();
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "update");
return props;
}
}
My project have this structure:
project structure

Why doesn't Redis call my MessageListener on __keyevent#*__:expired topic events?

I have recently upgraded Spring-Boot to 2.1.4.RELEASE and Spring-Cloud to Greenwich.SR1. My service is running on Java 11. My only dependency to Redis is through spring-boot-starter-data-redis. Although I did the configuration on Redis by setting notify-keyspace-events Ex, yet I don't seem to be able to receive any key expiry events from it. This is the first time I intend to receive such events for timeout purposes. What could have gone wrong?
Please help!
This is my RedisConfiguration:
#Configuration
public class RedisConfiguration {
#Value("${spring.redis.port}")
private String port;
#Value("${spring.redis.host}")
private String host;
#Value("${spring.redis.verification-code-topic}")
private String verificationCodeTopic;
#Bean
public RedisConnectionFactory redisConnectionFactory(){
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(host);
configuration.setPort(Integer.valueOf(port));
return new LettuceConnectionFactory(configuration);
}
#Bean
#Primary
public RedisTemplate<FundRedisKey, ResetPasswordRequest> resetPasswordRedisTemplate(){
RedisTemplate<FundRedisKey, ResetPasswordRequest> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setValueSerializer(resetPasswordRequestSerializer());
redisTemplate.setKeySerializer(redisKeySerializer());
return redisTemplate;
}
#Bean
public RedisTemplate<FundRedisKey, VerificationMessage> verificationMessageRedisTemplate(){
RedisTemplate<FundRedisKey, VerificationMessage> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setValueSerializer(verificationMessageSerializer());
redisTemplate.setKeySerializer(redisKeySerializer());
return redisTemplate;
}
#Bean
#Primary
public MessageListener verificationCodeMessageListener(){
return new VerificationCodeSubscriber(verificationMessageSerializer(),
resetPasswordRedisTemplate());
}
#Bean
public MessageListener resetPasswordTimeoutListener(){
return new ResetPasswordTimeoutSubscriber(resetPasswordRequestSerializer());
}
#Bean
#Primary
public MessageListenerAdapter verificationCodeMessageListenerAdapter(){
return new MessageListenerAdapter(verificationCodeMessageListener());
}
#Bean
public MessageListenerAdapter resetPasswordTimeoutMessageListenerAdapter(){
return new MessageListenerAdapter(resetPasswordTimeoutListener());
}
#Bean
public ChannelTopic verificationCodeTopic(){
return new ChannelTopic(verificationCodeTopic);
}
#Bean
#DependsOn(value = "taskExecutor")
public RedisMessageListenerContainer fundMessageListenerContainer(
#Qualifier("taskExecutor")Executor executor){
RedisMessageListenerContainer messageListenerContainer = new RedisMessageListenerContainer();
messageListenerContainer.setConnectionFactory(redisConnectionFactory());
messageListenerContainer.addMessageListener(
verificationCodeMessageListenerAdapter(), verificationCodeTopic());
messageListenerContainer.addMessageListener(
resetPasswordTimeoutMessageListenerAdapter(), new PatternTopic("__keyevent#*__:expired"));
messageListenerContainer.setTaskExecutor(executor);
return messageListenerContainer;
}
#Bean
public MessagePublisher verificationCodeMessagePublisher(){
return new VerificationCodePublisher(
verificationMessageRedisTemplate(), verificationCodeTopic());
}
#Bean
public RedisSerializer verificationMessageSerializer(){
return new Jackson2JsonRedisSerializer(VerificationMessage.class);
}
#Bean
#Primary
public RedisSerializer resetPasswordRequestSerializer(){
return new Jackson2JsonRedisSerializer(ResetPasswordRequest.class);
}
#Bean
public RedisSerializer redisKeySerializer(){
return new Jackson2JsonRedisSerializer(FundRedisKey.class);
}
}
And here is my ResetPasswordTimeoutSubscriber:
#Component
public class ResetPasswordTimeoutSubscriber implements MessageListener {
#Value("${spring.redis.key}")
private String key;
private final RedisSerializer messageSerializer;
public ResetPasswordTimeoutSubscriber(RedisSerializer messageSerializer){
this.messageSerializer = messageSerializer;
}
#Override
public void onMessage(Message message, byte[] bytes) {
ResetPasswordRequest resetPasswordRequest =
(ResetPasswordRequest)messageSerializer.deserialize(message.getBody());
//TODO Send operation timeout notification
}
}
Here is my TaskExecutor configuration
#Configuration
#EnableAsync
#EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
#Override
#Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("app-1-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
#Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
#Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(scheduledTaskExecutor());
}
#Bean
public ScheduledExecutorService scheduledTaskExecutor() {
return Executors.newScheduledThreadPool(jHipsterProperties.getAsync().getCorePoolSize());
}
}
I had not put an #Bean on my redisKeySerializer. I had posted the correct answer as question body.

Spring Security Java Config Troubles

I'm using Spring 4.1.6 and Spring Security 4.0.1
I'm trying to convert my Spring and Spring Security XML configurations over to Java config and have been stuck with the exception below for quite a while now...
... 25 more
Caused by: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$1.postProcess(WebSecurityConfigurerAdapter.java:78)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:171)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:67)
at csc.oceanlaw.config.SecurityConfig$$EnhancerBySpringCGLIB$$f2885b2e.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:369)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:323)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:105)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$80da63d.CGLIB$springSecurityFilterChain$0(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$80da63d$$FastClassBySpringCGLIB$$2a6cb227.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$80da63d.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 26 more
Here's my security config class:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String LOGIN_URL = "/login";
private static final String USER_BY_USERNAME_QUERY =
"select userName as username, password as password, 'true' as enabled " +
"from Users " +
"where (userName = ?)";
private static final String AUTHORITIES_BY_USERNAME_QUERY =
"select userName as username, role as authority " +
"from UserRoles " +
"where userName = ?";
private BasicDataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// Intercept-url config...
.authorizeRequests()
.antMatchers("/*").permitAll()
.antMatchers("/_a/**").hasRole("ROLE_USER")
.antMatchers("/_/**").hasRole("ROLE_USER")
.and()
.requiresChannel()
.anyRequest().requiresSecure()
.and()
// Login form config...
.formLogin()
.loginPage(LOGIN_URL)
.loginProcessingUrl("/j_spring_security_check")
.failureUrl("/login?err=1")
.successHandler(customAuthenticationHandler())
.usernameParameter("j_username")
.passwordParameter("j_password")
.and()
// Logout handling...
.logout()
.addLogoutHandler(logoutFilter())
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=1")
.and()
// Exception handling config...
.exceptionHandling()
.accessDeniedPage("/unauthorized")
.authenticationEntryPoint(ajaxAwareAuthenticationEntryPoint())
.and()
.csrf()
.disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.usersByUsernameQuery(USER_BY_USERNAME_QUERY)
.authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY)
.passwordEncoder(md5PasswordEncoder())
.dataSource(getDataSource());
};
#Bean
public AuthenticationFilter customAuthenticationHandler() {
return new AuthenticationFilter();
}
#Bean
public SecurityLogoutHandler logoutFilter() {
return new SecurityLogoutHandler();
}
#Bean
public AjaxAwareAuthenticationEntryPoint ajaxAwareAuthenticationEntryPoint() {
return new AjaxAwareAuthenticationEntryPoint(LOGIN_URL);
}
#Bean
public Md5PasswordEncoder md5PasswordEncoder() {
return new Md5PasswordEncoder();
}
#Bean
public DefaultRolesPrefixPostProcessor defaultRolesPrefixPostProcessor() {
return new DefaultRolesPrefixPostProcessor();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
public BasicDataSource getDataSource() {
dataSource = new PersistenceConfig().dataSource();
return dataSource;
}
public void setDataSource(BasicDataSource dataSource) {
this.dataSource = dataSource;
}
}
It seems to point out the security config, however, it may be elsewhere in the config classes. So, below is the rest of config...
Main Spring config:
#Configuration
#ComponentScan(
basePackages = {
"myproject.model",
"myproject.web",
"myproject.dao",
"myproject.dao.jpa",
"myproject.config"
}
)
public class MainConfig {
/**
* Apache commons config bean.
* #return {#link CompositeConfiguration}
*/
#Bean(name="config")
public CompositeConfiguration compositeConfiguration() throws ConfigurationException {
PropertiesConfiguration textProps = null;
PropertiesConfiguration validationProps = null;
PropertiesConfiguration configProps = null;
textProps = new PropertiesConfiguration("olsdmText.properties");
textProps.setReloadingStrategy(new FileChangedReloadingStrategy());
validationProps = new PropertiesConfiguration("ValidationMessages.properties");
validationProps.setReloadingStrategy(new FileChangedReloadingStrategy());
configProps = new PropertiesConfiguration("olsdmSettings.properties");
configProps.setReloadingStrategy(new FileChangedReloadingStrategy());
CompositeConfiguration bean = new CompositeConfiguration();
bean.addConfiguration(textProps);
bean.addConfiguration(validationProps);
bean.addConfiguration(configProps);
bean.setDelimiterParsingDisabled(false);
bean.setListDelimiter('|');
return bean;
}
}
Spring MVC config:
#Configuration
#EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurerAdapter {
#Inject org.apache.commons.configuration.Configuration config;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/docs/**").addResourceLocations("/docs");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
}
#Bean
public ViewResolver viewResolver() {
ContentNegotiatingViewResolver bean = new ContentNegotiatingViewResolver();
List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();
// Apache Tiles view resolver...
UrlBasedViewResolver tilesResolver = new UrlBasedViewResolver();
tilesResolver.setViewClass(TilesView.class);
tilesResolver.setOrder(0);
viewResolvers.add(tilesResolver);
// Default view resolver as a fallback. Allow view names to be served with just
// .jsp extension rather than a tiles id. This is primarily for AJAX calls that
// request a JSP resource...
InternalResourceViewResolver defaultResolver = new InternalResourceViewResolver();
defaultResolver.setPrefix(new String("/WEB-INF/views/"));
defaultResolver.setSuffix(new String(".jsp"));
defaultResolver.setOrder(1);
viewResolvers.add(defaultResolver);
bean.setViewResolvers(viewResolvers);
return bean;
}
/**
* Sets Apache Tiles XML config file location.
* #return {#link TilesConfigurer}
*/
#Bean
public TilesConfigurer tilesConfig() {
TilesConfigurer bean = new TilesConfigurer();
String[] definitions = {"/WEB-INF/views/tiles/config/tiles-config.xml"};
bean.setDefinitions(definitions);
return bean;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
#Bean
public PasswordGen passwordGen() {
return new PasswordGen();
}
#Bean
public Encrypt encrypt() {
return new Encrypt();
}
}
Datasource/JPA config:
#Configuration
#PropertySource("classpath:olsdmSettings.properties")
public class PersistenceConfig {
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.databaseUrl}")
private String databaseUrl;
#Value("${jdbc.userName}")
private String userName;
#Value("${jdbc.passWord}")
private String passWord;
#Value("${jdbc.validationQuery}")
private String validationQuery;
#Value("${jdbc.testWhileIdle}")
private boolean testWhileIdle;
#Value("${jdbc.maxTotal}")
private int maxTotal;
#Value("${jdbc.maxIdle}")
private int maxIdle;
#Value("${jdbc.maxWailMillis}")
private int maxWailMillis;
/**
* Sets datasource configuration.
* #return {#link BasicDataSource}
*/
#Bean(name="dataSource")
public BasicDataSource dataSource() {
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName(driverClassName);
bean.setUrl(databaseUrl);
bean.setUsername(userName);
bean.setPassword(passWord);
bean.setValidationQuery(validationQuery);
bean.setTestWhileIdle(testWhileIdle);
bean.setMaxTotal(maxTotal);
bean.setMaxIdle(maxIdle);
bean.setMaxWaitMillis(maxWailMillis);
return bean;
}
/**
* Sets application {#link LocalContainerEntityManagerFactoryBean}
* #return {#link LocalContainerEntityManagerFactoryBean}
*/
#Bean
public LocalContainerEntityManagerFactoryBean emf() {
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource());
return bean;
}
/**
* Sets application {#link JpaTransactionManager}
* #return {#link JpaTransactionManager}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager bean = new JpaTransactionManager();
bean.setEntityManagerFactory((EntityManagerFactory) emf());
return bean;
} */
#Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
emf().getObject());
return transactionManager;
}
/**
* Sets application {#link Jaxb2Marshaller}
* #return {#link Jaxb2Marshaller}
*/
#Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller bean = new Jaxb2Marshaller();
bean.setPackagesToScan(new String("myproject.model"));
return bean;
}
//To resolve ${} in #Value
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
WebApplicationIntializer implementation:
public class ApplicationInitializer implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "myproject.config";
private static final String MAPPING_URL = "/*";
#Override
public void onStartup(ServletContext container) throws ServletException {
WebApplicationContext context = getContext();
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic servlet =
container.addServlet("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping(MAPPING_URL);
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
return context;
}
}
Thanks a lot in advance for any help!
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public static final String CHARACTER_ENCODING = "UTF-8";
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{
WebMVCConfig.class,
PersistenceConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/*","/*"};
}
#Override
protected javax.servlet.Filter[] getServletFilters() {
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding(CHARACTER_ENCODING);
encodingFilter.setForceEncoding(true);
final OpenSessionInViewFilter openSessionInViewFilter = new OpenSessionInViewFilter();
return new Filter[] { encodingFilter, openSessionInViewFilter };
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
registerListener(servletContext);
}
private void registerListener(ServletContext servletContext) {
RequestContextListener requestContextListener = new RequestContextListener();
servletContext.addListener(requestContextListener);
}}
needs to #Override Class[] getRootConfigClasses method.that will make you configurer class as a configurer bean.so you can use #EnableWebSecurity and #Configuration in you configclass code.
hope this can help!
like this:
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{
WebMVCConfig.class,
PersistenceConfig.class};
}

Replace getBean with #Autowired for Service

Here I have my main class with #Service called RegionsServiceImpl. I'm initializing it with ApplicationContext.getBean, but I want to use #Autowired. And when I do, #Autowired doesn't initialize it.
Main class:
package com.rebel.shop;
public class JpaRepoTest {
//ApplicationContext ctx;
#Autowired
RegionsServiceImpl regionsServiceImpl;
public JpaRepoTest() {
// ctx = new AnnotationConfigApplicationContext(DataConfig.class);
// regionsServiceImpl = ctx.getBean("regionsServiceImpl", RegionsServiceImpl.class);
}
public static void main(String[] args) {
JpaRepoTest jpaRepoTest = new JpaRepoTest();
jpaRepoTest.testService();
}
private void testService() {
System.out.println(regionsServiceImpl.findById(3l).getName());
}
}
My Service class:
package com.rebel.shop.persistence.jpa.service;
#Service
public class RegionsServiceImpl implements RegionsService {
#Resource
private RegionsRepository regionsRepository;
#Override
public Regions findById(long id) {
return regionsRepository.findOne(id);
}
}
It's interface:
package com.rebel.shop.persistence.jpa.service;
public interface RegionsService {
public Regions findById(long id);
}
Repo:
package com.rebel.shop.persistence.jpa.repository;
public interface RegionsRepository extends JpaRepository<Regions, Long> {
}
And Java Config For Spring:
package com.rebel.shop.persistence.jpa.config;
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:app.properties")
#EnableJpaRepositories("com.rebel.shop.persistence.jpa.repository")
#ComponentScan("com.rebel.shop")
public class DataConfig {
private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PROP_ENTITYMANAGER_PACKAGES_TO_SCAN = "db.entitymanager.packages.to.scan";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(false);
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.rebel.shop.persistence.entity");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
// #Bean
// RegionsServiceImpl regionsServiceImpl() {
// return new RegionsServiceImpl();
// }
}
Thanks in advance!
UPD1:
Exception:
Exception in thread "main" java.lang.NullPointerException
at com.rebel.shop.JpaRepoTest.testService(JpaRepoTest.java:33)
at com.rebel.shop.JpaRepoTest.main(JpaRepoTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
You are not using the spring container, rather you are instantiating the object using new, hence no spring bean will be autowired, Modify your bean as below
package com.rebel.shop;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(DataConfig.class)
public class JpaRepoTest {
//ApplicationContext ctx;
#Autowired
RegionsServiceImpl regionsServiceImpl;
public JpaRepoTest() {
// ctx = new AnnotationConfigApplicationContext(DataConfig.class);
// regionsServiceImpl = ctx.getBean("regionsServiceImpl", RegionsServiceImpl.class);
}
#Test
public void mainMethod() {
testService();
}
private void testService() {
System.out.println(regionsServiceImpl.findById(3l).getName());
}
}

Vaadin + Spring Integration: Null Pointer exception

I have a Vaadin web application with UI class like this:
#SuppressWarnings("serial")
#Theme("mytheme")
public class LogsUI extends UI {
LogsView logsViewer = new LogsView();
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = LogsUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
Panel panel = new Panel();
panel.setContent(logsViewer);
panel.setSizeFull();
setContent(panel);
}
}
As u can see i add use setContent to add LogsView class which is a view - it is a fragment of declaration:
#SuppressWarnings("serial")
public class LogsView extends CustomComponent implements View {
//some variables, buttons, components etc
ProcessDao processDao;
//sample method
void sampleMethod(){
processDao = new ProcesDao;
processDao.getAllprocesses(); //just sample, no matter about logic
}
}
My ProcessDao class:
public class ProcessDao {
#Autowired
ApplicationConfiguration applicationConfiguration;
public ProcessDao() {
}
public List<ProcessEntity> getAllProcess(){
System.out.println("TEST:" + applicationConfiguration);
//entity manager and other stuffs
return processList;
}
}
As u can see i did System.out.println() to check if im getting applicationConfiguration object. Im getting null. This is main problem.
this is my ApplicationConfiguration class:
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = {"com.sample.project"})
#PropertySource({"classpath:jpa.postgresql.properties", "classpath:hibernate.properties"})
#EnableJpaRepositories(basePackages = {"com.sample.project.repo"})
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
#Value("${javax.persistence.jdbc.driver}")
private String driverClassName;
#Value("${javax.persistence.jdbc.url}")
private String databaseUrl;
#Value("${javax.persistence.jdbc.user}")
private String databaseUser;
#Value("${javax.persistence.jdbc.password}")
private String databasePassword;
#Value("${hibernate.dialect}")
private String dialect;
#Value("${hibernate.show_sql}")
private boolean showSQL;
#Value("${hibernate.hbm2ddl.auto}")
private String hbm2ddlAuto;
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
#PersistenceContext
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setJpaProperties(hibernateJPAProperties());
entityManagerFactoryBean.setPackagesToScan("com.sample.project");
return entityManagerFactoryBean;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(databaseUrl);
dataSource.setUsername(databaseUser);
dataSource.setPassword(databasePassword);
return dataSource;
}
public Properties hibernateJPAProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.show_sql", showSQL);
properties.put("hibernate.hbm2ddl.auto", hbm2ddlAuto);
return properties;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public FinancialProcessEntityDao financialProcessEntityDao() {
FinancialProcessEntityDao dao = new FinancialProcessEntityDao();
return dao;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Am i something missing? How to properly integrate my Vaadin app with Spring?
You should try this:
processDao = WebApplicationContextUtils.getRequiredWebApplicationContext(
VaadinServlet.getCurrent().getServletContext()).getBean(IProcessDao.class);
You can find some description here: link

Categories

Resources