最近在学习springboot时,发现controller 发送请求,返回NullPointerException,检查了好几遍配置,也没有发现具体问题,具体如下:
1.Application
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan("cn.no7player.mapper")
public class Application {
private static Logger logger = Logger.getLogger(String.valueOf(Application.class));
//DataSource配置
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
//提供SqlSeesion
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
/**
* Start
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
logger.info("SpringBoot Start Success");
}
}
2.UserService
@Service
public class UserService {
// @Autowired
private UserMapper userMapper;
public User getUserInfo(){
User user=userMapper.findUserInfo();
//User user=null;
return user;
}
}
3.model
package cn.no7player.model;
import java.io.Serializable;
public class User implements Serializable {
private String name;
private Integer age;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.mapper
public interface UserMapper {
public User findUserInfo();
}
5.mybatis的mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.no7player.mapper.UserMapper">
<select id="findUserInfo" resultType="cn.no7player.model.User">
select name, age,password from user;
</select>
</mapper>
6.controller
@Controller
public class UserController {
Logger logger = Logger.getLogger(String.valueOf(UserController.class));
@Autowired
private UserService userService;
@RequestMapping("/getUserInfo")
@ResponseBody
public User getUserInfo() {
User user = userService.getUserInfo();
if(user!=null){
System.out.println("user.getName():"+user.getName());
logger.info("user.getAge():"+user.getAge());
}
return user;
}
}
启动项目,发送post请求,控制台提示java.lang.NullPointerException: null
解决方法:检查注解,最后发现UserService中的UserMapper上少了个注解@Autowired,加上后问题得以解决。
网友评论