Vaadin + Spring Integration: Null Pointer exception - java

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

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

DataSource Router problem in multiples access of multiples datasources

I have project spring-boot using datasource routes in three diferents datasources.
This is my configuration:
#Configuration
#EnableCaching
public class CachingConfiguration extends CachingConfigurerSupport {
#Override
public KeyGenerator keyGenerator() {
return new EnvironmentAwareCacheKeyGenerator();
}
}
--
public class DatabaseContextHolder {
private static final ThreadLocal<DatabaseEnvironment> CONTEXT =
new ThreadLocal<>();
public static void set(DatabaseEnvironment databaseEnvironment) {
CONTEXT.set(databaseEnvironment);
}
public static DatabaseEnvironment getEnvironment() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
--
#Configuration
#EnableJpaRepositories(basePackageClasses = UsuarioRepository.class,
entityManagerFactoryRef = "customerEntityManager",
transactionManagerRef = "customerTransactionManager")
#EnableTransactionManagement
public class DatasourceConfiguration {
#Bean
#ConfigurationProperties(prefix = "spring.ciclocairu.datasource")
public DataSource ciclocairuDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix = "spring.palmas.datasource")
public DataSource palmasDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix = "spring.megabike.datasource")
public DataSource megabikeDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#Primary
public DataSource customerDataSource() {
DataSourceRouter router = new DataSourceRouter();
final HashMap<Object, Object> map = new HashMap<>(3);
map.put(DatabaseEnvironment.CICLOCAIRU, ciclocairuDataSource());
map.put(DatabaseEnvironment.PALMAS, palmasDataSource());
map.put(DatabaseEnvironment.MEGABIKE, megabikeDataSource());
router.setTargetDataSources(map);
return router;
}
#Autowired(required = false)
private PersistenceUnitManager persistenceUnitManager;
#Bean
#Primary
#ConfigurationProperties("spring.jpa")
public JpaProperties customerJpaProperties() {
return new JpaProperties();
}
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean customerEntityManager(
final JpaProperties customerJpaProperties) {
EntityManagerFactoryBuilder builder =
createEntityManagerFactoryBuilder(customerJpaProperties);
return builder.dataSource(customerDataSource()).packages(Users.class)
.persistenceUnit("customerEntityManager").build();
}
#Bean
#Primary
public JpaTransactionManager customerTransactionManager(
#Qualifier("customerEntityManager") final EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}
private JpaVendorAdapter createJpaVendorAdapter(
JpaProperties jpaProperties) {
AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(jpaProperties.isShowSql());
adapter.setDatabase(jpaProperties.getDatabase());
adapter.setDatabasePlatform(jpaProperties.getDatabasePlatform());
//adapter.setGenerateDdl(jpaProperties.isGenerateDdl());
return adapter;
}
private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(
JpaProperties customerJpaProperties) {
JpaVendorAdapter jpaVendorAdapter =
createJpaVendorAdapter(customerJpaProperties);
return new EntityManagerFactoryBuilder(jpaVendorAdapter,
customerJpaProperties.getProperties(), this.persistenceUnitManager);
}
}
--
public class DataSourceRouter extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
if(DatabaseContextHolder.getEnvironment() == null)
DatabaseContextHolder.set(DatabaseEnvironment.CICLOCAIRU);
return DatabaseContextHolder.getEnvironment();
}
}
--
public class EnvironmentAwareCacheKeyGenerator implements KeyGenerator {
#Override
public Object generate(Object target, Method method, Object... params) {
String key = DatabaseContextHolder.getEnvironment().name() + "-" + (
method == null ? "" : method.getName() + "-") + StringUtils
.collectionToDelimitedString(Arrays.asList(params), "-");
return key;
}
}
I set datasource using
DatabaseContextHolder.set(DatabaseEnvironment.CICLOCAIRU);
Go to problem:
For example, two users in diferents datasources: 1 and 2
if one user using datasource 1, and send a request,
The other user that using datasource 2,
yours next request , instead of datasource 2, this get datasource 1. I think that this ThreadLocal<DatabaseEnvironment> CONTEXT =
new ThreadLocal<>(); was exclusive for request, But this does not seem to be so.
Iam sorry if this not be clear.
In realy, i need that DataSurceRouter were exclusive for each request, and an request not intefer in another.
I wrong about i think of DatasourceRouter or my code is bad ?
The issue probably occurs because of server thread pool: you have a given number of threads, and each request is served rolling among them.
When the server recycles a thread, the thread local variable has that value already set from the previous cycle, so you need to flush that value after each request, leaving the thread in a clean state.

Using PropertySourcesPlaceholderConfigurer to retrieve values from properties file as well as database

I am new to Spring Boot. I am trying to achieve a PropertySourcesPlaceholderConfigurer configuration that would return properties from a property file as well as database table. Here's what I wrote:
#Configuration
#PropertySource(value = { "classpath:application.properties" }, ignoreResourceNotFound = false)
public class SpringPropertiesConfig implements EnvironmentAware {
private static final Logger log = LoggerFactory.getLogger(SpringPropertiesConfig.class);
#Inject
private org.springframework.core.env.Environment env;
#PostConstruct
public void initializeDatabasePropertySourceUsage() {
MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
System.out.println("propertySources : " + propertySources);
try {
// dataSource, Table Name, Key Column, Value Column
DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration(dataSource(),
"APPLICATION_CONFIGURATION", "KEY", "VALUE");
Properties dbProps = ConfigurationConverter.getProperties(databaseConfiguration);
PropertiesPropertySource dbPropertySource = new PropertiesPropertySource("dbPropertySource", dbProps);
propertySources.addFirst(dbPropertySource);
} catch (Exception e) {
log.error("Error during database properties setup", e);
throw new RuntimeException(e);
}
}
#Bean(name = "pspc")
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
pspc.setIgnoreUnresolvablePlaceholders(true);
// System.out.println("propertySourcesPlaceholderConfigurer = " +
// pspc.getAppliedPropertySources());
return pspc;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("dev.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("dev.datasource.url"));
dataSource.setUsername(env.getProperty("dev.datasource.username"));
dataSource.setPassword(env.getProperty("dev.datasource.password"));
return dataSource;
}
#Override
public void setEnvironment(Environment paramEnvironment) {
this.env = paramEnvironment;
}
}
I found that properties from application.properties were getting resolved correctly.
#Value("${spnego.defaultRealm}")
private String defRealm;
Here, 'defRealm' contained the correct value. However properties from database were not getting resolved.
#Value("${enviromentName}")
private String envir;
If I print the value of envir, it prints '${enviromentName}'.
In the SpringPropertiesConfig class, the table is getting read correctly and the Properties object 'dbProps' prints all the rows in the APPLICATION_CONFIGURATION table.
Any ideas?
Thank you M. Deinum, I followed your suggestion and implemented the following :
public class SpringPropertiesConfig implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public DataSource getDataSource(org.springframework.core.env.PropertySource<?> propSrc) {
String profile = (String) propSrc.getProperty("spring.profiles.active");
if (profile.equals("dev")) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName((String) propSrc.getProperty("dev.datasource.driver-class-name"));
dataSource.setUrl((String) propSrc.getProperty("dev.datasource.url"));
dataSource.setUsername((String) propSrc.getProperty("dev.datasource.username"));
dataSource.setPassword((String) propSrc.getProperty("dev.datasource.password"));
return dataSource;
} else if (profile.equals("prod")) {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
DataSource dataSource = dataSourceLookup
.getDataSource((String) propSrc.getProperty("prd.datasource.jndi-name"));
return dataSource;
}
return null;
}
#Override
public void initialize(ConfigurableApplicationContext ctx) {
org.springframework.core.env.PropertySource<?> p = ctx.getEnvironment().getPropertySources()
.get("applicationConfigurationProperties");
DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration(getDataSource(p),
"APPLICATION_CONFIGURATION", "KEY", "VALUE");
System.out.println("databaseConfiguration created : " + databaseConfiguration);
Properties dbProps = ConfigurationConverter.getProperties(databaseConfiguration);
System.out.println("dbProps=" + dbProps);
PropertiesPropertySource dbPropertySource = new PropertiesPropertySource("dbPropertySource", dbProps);
ctx.getEnvironment().getPropertySources().addFirst(dbPropertySource);
}
}
But what i am not sure is whether
org.springframework.core.env.PropertySource<?> p = ctx.getEnvironment().getPropertySources().get("applicationConfigurationProperties");
is the best way to read from application.properties file.
The above ApplicationContextInitializer is registered with Spring as follows -
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(final String[] args) {
new SpringApplicationBuilder(Application.class).initializers(new SpringPropertiesConfig()).run(args);
}
#Bean
public RestTemplate restTemplate(final RestTemplateBuilder builder) {
return builder.build();
}
}

Use of Transactional annotation in Spring data with Hibernate

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;
}
}

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());
}
}

Categories

Resources