0

I wrote the following code but I cannot make it work. I don't know where is the problem.

All classes are in the "hello" package.

public static void main(String args[]) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.scan("hello");
        applicationContext.refresh();

        ApplicationService app = new ApplicationService();
        app.run();

        applicationContext.close();
    }


@Component
public class ApplicationService {

    @Autowired
    @Qualifier("main")
    private SimpleDriverDataSource dataSourcee;

    public void run(){
!!!!!!!!            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourcee);
    }


}

@Configuration
public class Config {

    @Bean
    @Qualifier("main")
    public SimpleDriverDataSource getDataSource() {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(org.h2.Driver.class);
        dataSource.setUsername("sa");
        dataSource.setUrl("jdbc:h2:mem");
        dataSource.setPassword("");
        return dataSource;
    }
}

I tried in a lot of ways and combinations and I still get the following error. I tried without a qualifier, I changed the name of the method in Config, I tried to name the bean differently but I got no results. Where is the problem?

Exception in thread "main" java.lang.IllegalArgumentException: Property 'dataSource' is required
    at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:135)
    at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:169)
    at hello.ApplicationService.run(ApplicationService.java:28)
    at hello.AppMain.main(AppMain.java:12)
tzortzik
  • 4,993
  • 9
  • 57
  • 88
  • Try using 'dataSource' as the qualified name... – Mechkov Dec 03 '14 at 17:56
  • Same result even with the same qualified name. – tzortzik Dec 03 '14 at 17:58
  • The answer in not in the linked topic. I already tried the solutions. – tzortzik Dec 03 '14 at 18:11
  • 1
    I'm just gonna quote the first sentence of the answer given there: _The field annotated `@Autowired` is `null` because Spring doesn't know about the copy of `MileageFeeCalculator` that you created with `new` and didn't know to autowire it._ How did you create your `ApplicationService` object on which you call `run`? – Sotirios Delimanolis Dec 03 '14 at 18:14
  • I got the idea. It's working now. Now you pointed the solution. Thank you! – tzortzik Dec 03 '14 at 18:22
  • 1
    Always be careful with `null` in `@Autowired` targets. Spring will **never** (almost) leave such a field as `null`. Instead, it would throw an exception. There must be something else going on in those cases. – Sotirios Delimanolis Dec 03 '14 at 18:25

0 Answers0