java spring bean annotation @Autowired无效

时间:2014-12-03 17:53:51

标签: java spring javabeans autowired

我编写了以下代码,但我无法使其工作。我不知道问题出在哪里。

所有课程都在“hello”包中。

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

我尝试了很多方法和组合,但仍然会出现以下错误。我尝试没有限定符,我在Config中更改了方法的名称,我尝试以不同的方式命名bean但我没有得到任何结果。问题在哪里?

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)

0 个答案:

没有答案
相关问题