NullPointerException trying to Autowire Service in Java Application (Spring) - java

I am writing a Java Application that is going to be using Spring, Hibernate and more its going to be packaged in a Jar and run from the command like.
My main class looks like the following right now:
public class App
{
private static final Logger logger = LoggerFactory.getLogger(App.class);
#Autowired
private static MemberInquiryService memberInquiryService;
public static void main(String[] args )
{
logger.info("Starting Inquiry Batch Process");
int pendingRecords = memberInquiryService.getPendingRecordCount();
logger.info("Current Number Of Pendinig Records (" + pendingRecords + ")");
logger.info("Ending Inquiry Batch Process");
}
}
and in the getPendingRecordCount I am just return "10" for testing:
public int getPendingRecordCount()
{
return 10;
};
Why would I be getting the following error:
Exception in thread "main" java.lang.NullPointerException
at org.XXXX.inquirybatch.app.App.main(App.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Also here is my DatabaseConfig.class
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages= { "org.xxxx.inquirybatch", "org.xxxx.core" })
#PropertySource("classpath:application.properties")
public class DatabaseConfig {
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);
#Autowired
Environment env;
#Bean
public DataSource dataSource() {
String serverType = env.getProperty("server.type");
try {
if(serverType.equalsIgnoreCase("tomcat"))
{
com.mchange.v2.c3p0.ComboPooledDataSource ds = new com.mchange.v2.c3p0.ComboPooledDataSource();
ds.setDriverClass(env.getProperty("database.driver"));
ds.setUser(env.getProperty("database.user"));
ds.setPassword(env.getProperty("database.password"));
ds.setJdbcUrl(env.getProperty("database.url"));
return ds;
}
else
{
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB");
}
}
catch (Exception e)
{
logger.error(e.getMessage());
}
return null;
}
#Bean
public SessionFactory sessionFactory()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setPackagesToScan(new String[] { "org.xxxx.inquirybatch.model", "org.xxxx.core.model" } );
try {
factoryBean.afterPropertiesSet();
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return factoryBean.getObject();
}
#Bean
public Properties getHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));
//Audit History flags
hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));
return hibernateProperties;
}
#Bean
public HibernateTransactionManager hibernateTransactionManager()
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory());
htm.afterPropertiesSet();
return htm;
}
}

Spring never injects static fields. And it only inject objects that are retrieved from the application context, or are themselves injected into other objects.
You're not even creating an application context in your program, so Spring doesn't play any role in this program.
I suggest to read the documentation.

You need to get the memberInquiryService from ClassPathXmlApplicationContext
For example :-
ApplicationContext context= new ClassPathXmlApplicationContext("spring config.xml");
MmberInquiryService memberInquiryService = context.getBean("memberInquiryService ");
basically in your code snippet MemberInquiryService is not spring managed as you are not getting from spring container. Also you need to declare MmberInquiryService entry in spring config.xml

I had to change the main class to..
public static void main(String[] args )
{
logger.info("Starting Inquiry Batch Process");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MemberInquiryService memberInquiryService = (MemberInquiryService) context.getBean("memberInquiryService");
int pendingRecords = memberInquiryService.getPendingRecordCount();
logger.info("Current Number Of Pendinig Records (" + pendingRecords + ")");
logger.info("Ending Inquiry Batch Process");
}

Related

How can I use java configuration of spring batch without spring boot?

I'm new to spring batch and I'm trying to learn about it.
I implemented datasource and batch configuration but it doesn't seem to work, because
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID, JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table '$tableName.batch_job_instance' doesn't exist
DataSourceConfiguration class :
#Configuration
public class DataSourceConfiguration {
#Bean
public DataSource mysqlDataSource() throws SQLException {
final SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriver(new com.mysql.cj.jdbc.Driver());
dataSource.setUrl("jdbc:mysql://localhost:3306/task4");
dataSource.setUsername("name");
dataSource.setPassword("password");
return dataSource;
}
}
And I have Batch configuration class, but I dont know #EnableBatchProcessing annotation works without springboot
#Configuration
#EnableBatchProcessing
#Import(DataSourceConfiguration.class)
public class BatchConfiguration {
#Autowired
private JobBuilderFactory jobs;
#Autowired
private StepBuilderFactory steps;
#Autowired
private DataSource dataSource;
#Bean
public ItemReader<User> itemReader() {
return new JdbcCursorItemReaderBuilder<User>()
.dataSource(this.dataSource)
.name("creditReader")
.sql("select userLogin, userEmail, userPassword, accountBalance from userInfo")
.rowMapper(new UserRowMapper())
.build();
}
#Bean
public ItemWriter<User> simpleItemWriter(){
return new SimpleUserWriter();
}
#Bean
public Job sampleJob() {
return this.jobs.get("sampleJob")
.start(step1())
.build();
}
#Bean
public Step step1() {
return this.steps.get("step1")
.<User,User>chunk(10)
.reader(itemReader())
.writer(simpleItemWriter())
.build();
}
}
Main class contains those lines of code :
public class Demo {
public static void main(String[] args) throws SQLException {
ApplicationContext context = new AnnotationConfigApplicationContext(BatchConfiguration.class);
context.getBean("jobRepository");
JobLauncher jobLauncher = context.getBean("jobLauncher",JobLauncher.class);
Job job = context.getBean("sampleJob", Job.class);
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Job Exit Status : "+ execution.getStatus());
} catch (JobExecutionException e) {
System.out.println("Job ExamResult failed");
e.printStackTrace();
}
}
}
How can I solve this problem?Thanks for helping
The error seems to say that you are missing the tables needed by Spring batch.
Check https://docs.spring.io/spring-batch/docs/4.3.x/reference/html/schema-appendix.html
You can also find SQL files ready for the different DB engine under org/springframework/bacth/core/schema-<DB>.sql in the spring batch core jar file

Error on setting ConnectionInitSql with Hikari Version : 3.4.5

I am getting the following error when I upgrade my Hikari version to 3.4.5
The configuration of the pool is sealed once started. Use HikariConfigMXBean for runtime changes.
I am running the following #BeforeEach test
dataSource.getHikariPoolMXBean().softEvictConnections();
dataSource.setConnectionInitSql("set search_path to " + getTestSchema() + ", public");
This is how I load my DataSource
public class DataSource {
private static HikariConfig config = new HikariConfig();
public static HikariDataSource ds;
static {
config.setJdbcUrl(
System.getProperty("jdbc.url", "jdbc:postgresql://localhost:123/abc"));
config.setUsername(System.getProperty("username", "xyz"));
config.setPassword(System.getProperty("password", "123"));
ds = new HikariDataSource(config);
}
private DataSource() {}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void evictConnection(Connection connection) {
ds.evictConnection(connection);
}
}
class TestClass extends DatabaseTestCase {
#Autowired
private HikariDataSource dataSource;
#BeforeEach
void initData() throws SQLException {
DataSource.ds = dataSource;
dataSource.getHikariPoolMXBean().softEvictConnections();
dataSource.setConnectionInitSql("set search_path to " + getTestVitmSchema() + ", public");
}
This is how I setSchema for the Test Cases
public abstract class DatabaseTestCase {
private String testSchema;
#BeforeEach
final void setupSchema() {
int classHash = Math.abs(getClass().getSimpleName().hashCode());
testSchema = String.format("test_%s", classHash);
Map<String, String> placeholders = new HashMap<>();
placeholders.put("schema", testSchema);
placeholders.put("name", "xyz");
placeholders.put("password", "123");
placeholders.putAll(getPlaceholderReplacement());
Flyway flyway =
Flyway.configure()
.dataSource(DataSource.ds)
.schemas(testSchema)
.placeholders(placeholders)
.load();
flyway.migrate();
}
How can I set Connection Init Sql without getting the error. Thank you.
You can't. You will need to create a new dataSource to do this. You can see why from looking at the source code.

BeanCurrentlyInCreationException when setting DataSource in Spring Boot and Batch project

I am using both Spring Boot and Batch in a maven multi-module project for parsing CSV files and storing data in a MySQL database.
When running the batch module using my BatchLauncher class (shared below) I get a BeanCurrentlyInCreationException caused by getDataBase() which I use for configuring my MySQL database. (click this link to see logs)
And when I remove this method Spring Boot choose automatically an embedded database of type H2 (link for logs)
BatchLauncher class :
#Slf4j
public class BatchLauncher {
public static void main(String[] args) {
try {
Launcher.launchWithConfig("My Batch", BatchConfig.class, false);
}catch (Exception ex) {
log.error(ex.getMessage());
}
}
}
Launcher class :
#Slf4j
public class Launcher {
private Launcher() {}
public static void launchWithConfig(String batchName, Class<?> configClass, boolean oncePerDayMax) throws JobExecutionException, BatchException {
try {
// Check the spring profiles used
log.info("Start batch \"" + batchName + "\" with profiles : " + System.getProperty("spring.profiles.active"));
// Load configuration
#SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
//Authorize only one execution of each job per day
JobParameters jobParameters = new JobParameters();
JobExecution execution = jobLauncher.run(job, jobParameters);
if(!BatchStatus.COMPLETED.equals(execution.getStatus())) {
throw new BatchException("Unknown error while executing batch : " + batchName);
}
}catch (Exception ex){
log.error("Exception",ex);
throw new BatchException(ex.getMessage());
}
}
}
BatchConfig class :
#Slf4j
#Configuration
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#EnableBatchProcessing
#ComponentScan(basePackages = {
"fr.payet.flad.batch.tasklet",
"fr.payet.flad.batch.mapper"
})
#Import({CoreConfig.class})
public class BatchConfig {
private StepBuilderFactory steps;
private JobBuilderFactory jobBuilderFactory;
private ReadInputTasklet readInputTasklet;
public BatchConfig(StepBuilderFactory steps, JobBuilderFactory jobBuilderFactory, ReadInputTasklet readInputTasklet) {
this.steps = steps;
this.jobBuilderFactory = jobBuilderFactory;
this.readInputTasklet = readInputTasklet;
}
#Bean
public DataSource getDataBase(){
return DataSourceBuilder
.create()
.driverClassName("com.mysql.jdbc.Driver")
.url("jdbc:mysql://localhost:3306/myDb?useSSL=false")
.username("myuser")
.password("mypwd")
.build();
}
#Bean
public Step readInputStep() {
return steps.get("readInputStep")
.tasklet(readInputTasklet)
.build();
}
#Bean
public Job readCsvJob() {
return jobBuilderFactory.get("readCsvJob")
.incrementer(new RunIdIncrementer())
.flow(readInputStep())
.end()
.build();
}
}
The solution was to create a custom DataSourceConfiguration class annotated with #Configuration in which I set my own database like this :
#Bean
public DataSource getDataBase(){
return DataSourceBuilder
.create()
.driverClassName("com.mysql.jdbc.Driver")
.url("jdbc:mysql://localhost:3306/myDB?useSSL=false")
.username("myUser")
.password("myPwd")
.build();
}

New to HSQLDB working with Spring Application with JavaConfig. I dont see database starting up?

I am New to HSQLDB working with Spring Application with JavaConfig. I dont see database starting up?.. I know I must be doing something wrong.
Here is my databaeconfig
public class DatabaseConfig
{
private static final Logger LOGGER = getLogger(DatabaseConfig.class);
#Autowired
Environment env;
#Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL).
addScript("schema.sql").build();
return db;
}
#Bean
public DataSource hsqlDataSource() {
BasicDataSource ds = new BasicDataSource();
try {
ds.setDriverClassName("org.hsqldb.jdbcDriver");
ds.setUsername("sa");
ds.setPassword("");
ds.setUrl("jdbc:hsqldb:mem:mydb");
}
catch (Exception e)
{
LOGGER.error(e.getMessage());
}
return ds;
}
#Bean
public SessionFactory sessionFactory()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(hsqlDataSource());
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setPackagesToScan(new String[]{"com.xxx.model"});
try
{
factoryBean.afterPropertiesSet();
} catch (IOException e)
{
LOGGER.error(e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return factoryBean.getObject();
}
#Bean
public Properties getHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));
//Audit History flags
hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));
return hibernateProperties;
}
#Bean
public HibernateTransactionManager hibernateTransactionManager()
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory());
htm.afterPropertiesSet();
return htm;
}
}
Here is my main class:
public class MainApp
{
private static final Logger LOGGER = getLogger(MainApp.class);
#Autowired
protected static MessageService mService;
public static void main(String[] args)
{
ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = context.getBean(HelloWorld.class);
/**
* Date: 4/26/13 / 9:26 AM
*
* Comments:
*
* I added Log4J to the example.
*/
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
Message message = new Message();
message.setMessage(helloWorld.getMessage());
mService.SaveMessage(message);
helloWorld.setMessage("I am in Staten Island, New York");
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
}
Below is the only error I see on the trying to save data to the database... I dont see anything about the database starting on my console
Message from HelloWorld Bean: I love New York.
Exception in thread "main" java.lang.NullPointerException
You can download the source and read about this issue at the following:
https://github.com/JohnathanMarkSmith/HelloSpringJavaBasedJavaConfig/issues/1
Did you try to annotate DatabaseConfig with the #Component annotation?

New to HSQLDB working with Spring Application with JavaConfig

I am New to HSQLDB and working with Spring Application with JavaConfig. I want my example to setup a in memory database(HSQLDB) and insert one row.
I think I have my stuff all in order but I don't know where to create the database and the tables.
Below is my main.app code
public class MainApp
{
private static final Logger LOGGER = getLogger(MainApp.class);
#Autowired
protected MessageService mService;
public static void main(String[] args)
{
ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = context.getBean(HelloWorld.class);
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
/**
* I removed the following line... we are now using log4j
*/
//System.out.println(helloWorld.getMessage());
helloWorld.setMessage("I am in Staten Island, New York");
/**
* I removed the following line... we are now using log4j
*/
//System.out.println(helloWorld.getMessage());
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
}
and here is my DatabaseConfig.class
public class DatabaseConfig
{
private static final Logger LOGGER = getLogger(DatabaseConfig.class);
#Autowired
Environment env;
#Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
#Bean
public SessionFactory sessionFactory()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setPackagesToScan(new String[]{"com.xxxx.model"});
try
{
factoryBean.afterPropertiesSet();
} catch (IOException e)
{
LOGGER.error(e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return factoryBean.getObject();
}
#Bean
public Properties getHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.use_sql_comments", env.getProperty("hibernate.use_sql_comments"));
hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
hibernateProperties.setProperty("javax.persistence.validation.mode", env.getProperty("javax.persistence.validation.mode"));
//Audit History flags
hibernateProperties.setProperty("org.hibernate.envers.store_data_at_delete", env.getProperty("org.hibernate.envers.store_data_at_delete"));
hibernateProperties.setProperty("org.hibernate.envers.global_with_modified_flag", env.getProperty("org.hibernate.envers.global_with_modified_flag"));
return hibernateProperties;
}
#Bean
public HibernateTransactionManager hibernateTransactionManager()
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory());
htm.afterPropertiesSet();
return htm;
}
but I don't know where the database is create and how do I insert my table before my project runs?
You can download the source code at the following:
https://github.com/JohnathanMarkSmith/HelloSpringJavaBasedJavaConfig/issues/1
This has been asked before, take a look at Startup script to create a schema in HSQLDB

Categories