尝试使用@AutoWire功能时,其中一个StandAlone应用程序无法执行此操作,而是获取空指针异常。请突出我的错误,如果有的话。非常感谢您的帮助。
Spring Ver 5.1.5.RELEASE并且我们没有使用任何xml配置文件来告诉spring有一些注释类,而是使用AppConfig顶部的@ComponentScan或@EnableAutoConfiguration,并将main()类中的Context绑定为第一行。但是,Autowiring与jdk(Environment)的内部bean / java类完美配合,但不适用于自定义POJO类。如果我们试图通过getBean方法,那么它的工作原理。但我试图避免在任何地方创建上下文并使用getBean()请参阅下面的内容并仅使用您的宝贵指南帮助我。
public class ContextMaster {
private static AnnotationConfigApplicationContext appContext;
public static AnnotationConfigApplicationContext getApplicationContext() {
if (appContext == null) {
appContext = new AnnotationConfigApplicationContext(ContextConfig.class);
//appContext = new AnnotationConfigApplicationContext("com.xx.xx.xxx","xx.xxx.xxxx.xxx.datamanager");
logger.debug("Context Invoked !!");
}
return appContext;
}
}
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = {
@ComponentScan(basePackages = "xxxxx.datamanager"),
@ComponentScan(basePackages = "com.xx.xx.xxx"),
@ComponentScan(basePackages = "com.xx.xx.xxx.utils")})
public class AppConfig {
@Autowired
private Environment env;
@Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
return dataSource;
}
@Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
//LocalSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
factoryBean.setDataSource(getDataSource());
Properties props=new Properties();
props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
props.put("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
factoryBean.setHibernateProperties(props);
factoryBean.setAnnotatedClasses(xx.class, xxxx.class, xxxx.class, xxx.class);
return factoryBean;
}
@Bean
public HibernateTransactionManager getTransactionManager() {
return transactionManager;
}
}
// Here is NPE thrown when tried with auto-configured bean
@Component
public class Good extends Good11 {
@Autowired
private RxxxDyyyyHelper rdh;
//RxxxDyyyyHelper rdh =
ContextHelper.getApplicationContext().getBean(RxxxDyyyyHelper .class);
rdh.setProperty(); // NPE here
rdh.getProperty(); // NPE
}
// Here we're trying to initiate the LosUtils class
public class LosUtils {
public static void main(String args[]) throws Exception {
AnnotationConfigApplicationContext applicationContext = `ContextHelper.getApplicationContext();`
}
看起来你没有把完整的代码放在这里,因为你的Good
类不会这样编译..