[英]NullPointerException while using @Autowired with Jersey + Spring frameworks
[英]NullPointerException while using @Autowired
我正在使用 picocli,这里是 class,我在尝试使用teacherService.addTeacher()
时捕获 NPE 异常:
@CommandLine.Command
@Component
public class TeacherServiceCommand implements Runnable {
@Autowired
TeacherService teacherService;
public static void main(String[] args) {
new TeacherServiceCommand().run();
}
@Override
public void run() {
AnnotationConfigApplicationContext contextClass = new AnnotationConfigApplicationContext(AppConfig.class);
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
Teacher teacher = new Teacher(117,"test","test");
teacherService.addTeacher(teacher);
}
AppConfig.class:
@Configuration
@ComponentScan("com.foxminded.uviversity")
@PropertySource("classpath:db.properties")
public class AppConfig {
private static final String URL = "URL";
private static final String USER = "USER";
private static final String DRIVER = "DRIVER";
private static final String PASSWORD = "PASSWORD";
@Autowired
Environment environment;
@Bean
DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(environment.getProperty(URL));
driverManagerDataSource.setUsername(environment.getProperty(USER));
driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER));
return driverManagerDataSource;
}
@Bean
TeacherService teacherService(DataSource dataSource) {
return new TeacherServiceImpl(dataSource);
}
}
TeacherService 是接口。
TeacherServiceImpl 实现 TeacherService:
@Component
public class TeacherServiceImpl implements TeacherService {
private static final String SQL_INSERT_TEACHER = "INSERT INTO teachers(teacher_id, teacher_name, position) VALUES (?,?,?)";
JdbcTemplate jdbcTemplate;
@Autowired
public TeacherServiceImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public boolean addTeacher(Teacher teacher) {
return jdbcTemplate.update(SQL_INSERT_TEACHER, teacher.getTeacherId(), teacher.getTeacherName(), teacher.getPosition()) > 0;
}
也许在某个地方我对注释或类似的东西感到困惑。 预先感谢您的每一个帮助!
applicationContext.xml
文件仅用于初始化数据库。
<jdbc:initialize-database>
<jdbc:script location="classpath:schema.sql"/>
</jdbc:initialize-database>
我运行 SQL 脚本在application.xml
中创建表。
如果您知道如何通过 Annotations 初始化数据库,我将不胜感激!
完整的堆栈跟踪:
May 08, 2020 10:18:08 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@433c675d: startup date [Fri May 08 10:18:08 EEST 2020]; root of context hierarchy
May 08, 2020 10:18:08 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'teacherService' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=universityConfiguration; factoryMethodName=teacherService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/foxminded/university/UniversityConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=appConfig; factoryMethodName=teacherService; initMethodName=null; destroyMethodName=(inferred); defined in com.foxminded.university.config.AppConfig]
May 08, 2020 10:18:08 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
May 08, 2020 10:18:08 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@78dd667e: startup date [Fri May 08 10:18:08 EEST 2020]; root of context hierarchy
May 08, 2020 10:18:08 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
May 08, 2020 10:18:09 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'teacherService' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=appConfig; factoryMethodName=teacherService; initMethodName=null; destroyMethodName=(inferred); defined in com.foxminded.university.config.AppConfig] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=universityConfiguration; factoryMethodName=teacherService; initMethodName=null; destroyMethodName=(inferred); defined in com.foxminded.university.UniversityConfiguration]
May 08, 2020 10:18:09 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
May 08, 2020 10:18:09 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing SQL script from class path resource [schema.sql]
May 08, 2020 10:18:10 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executed SQL script from class path resource [schema.sql] in 1162 ms.
Exception in thread "main" java.lang.NullPointerException
at com.foxminded.university.cli.TeacherServiceCommand.run(TeacherServiceCommand.java:44)
at com.foxminded.university.cli.TeacherServiceCommand.main(TeacherServiceCommand.java:32)
Stacktrace after removing `teacherService` bean creation from `AppConfig` and marked `TeacherServiceImpl`with annotation `@Service` :
May 08, 2020 10:58:09 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@433c675d: startup date [Fri May 08 10:58:09 EEST 2020]; root of context hierarchy
May 08, 2020 10:58:10 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
May 08, 2020 10:58:10 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@290d210d: startup date [Fri May 08 10:58:10 EEST 2020]; root of context hierarchy
May 08, 2020 10:58:10 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
May 08, 2020 10:58:10 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.postgresql.Driver
May 08, 2020 10:58:10 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing SQL script from class path resource [schema.sql]
May 08, 2020 10:58:11 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executed SQL script from class path resource [schema.sql] in 1108 ms.
Exception in thread "main" java.lang.NullPointerException
at com.foxminded.university.cli.TeacherServiceCommand.run(TeacherServiceCommand.java:49)
at com.foxminded.university.cli.TeacherServiceCommand.main(TeacherServiceCommand.java:36)
而不是直接调用run
方法
public static void main(String[] args) {
new TeacherServiceCommand().run();
}
要使用 picocli 进行命令行参数解析,您需要创建picocli.CommandLine
object 并调用其execute
方法。 要获得 Spring 服务注入,请使用PicocliSpringFactory
picocli-spring-boot-starter
模块中的 PicocliSpringFactory。
import org.springframework.context.ApplicationContext;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.spring.PicocliSpringFactory;
@Command(name = "teacherservice", mixinStandardHelpOptions = true)
@Component
public class TeacherServiceCommand implements Runnable {
@Autowired
TeacherService teacherService;
public static void main(String[] args) {
AnnotationConfigApplicationContext contextClass = new AnnotationConfigApplicationContext(AppConfig.class);
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
new CommandLine(TeacherServiceCommand.class, new PicocliSpringFactory(context))
.execute(args); // this calls run after parsing the command line args
}
@Override
public void run() {
Teacher teacher = new Teacher(117,"test","test");
teacherService.addTeacher(teacher);
}
}
有关更多详细信息和示例,另请参阅https://github.com/remkop/picocli/tree/master/picocli-spring-boot-starter 。
这可能是由于
new TeacherServiceCommand().run();
而不是自动装配 TeacherService。 你能从下面的 run 方法中的 spring 上下文中检索它,看看它是否有帮助。
TeacherService teacherService = context.getBean(TeacherService.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.