我有以下代码尝试使用Spring Mongo Repository将POJO对象(Actor)保存到MongoDB中,但存储库对象始终为Null。我已经关注了多个示例,但主要是this one
POJO课程:
@Document(collection = "actors")
public class Actor
{
@Id
private String id;
...
//constructor
//setters & getters
}
存储库:
public interface ActorRepository extends MongoRepository<Actor, String>
{
public Actor findByFNameAndLName(String fName, String lName);
public Actor findByFName (String fName);
public Actor findByLName(String lName);
}
使用存储库的服务:
@Service
public class ActorService
{
@Autowired
private ActorRepository actorRepository;
public Actor insert(Actor a)
{
a.setId(null);
return actorRepository.save(a);
}
}
我从REST控制器类访问该服务:
@RestController
public class Controllers
{
private static final Logger logger = Logger.getLogger(Controllers.class);
private static final ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
private ActorService actorService = new ActorService();
@RequestMapping(value="/createActor", method=RequestMethod.POST)
public @ResponseBody String createActor(@RequestParam(value = "fName") String fName,
@RequestParam(value = "lName") String lName,
@RequestParam(value = "role") String role)
{
return actorService.insert(new Actor(null,fName,lName,role)).toString();
}
...
}
我得到的错误是此行中的NullPointerException:return actorRepository.save(a);
方法中的ActorService.insert()
。
任何想法为什么会发生这种情况?
编辑:以下是Spring配置
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration
{
@Bean
public GridFsTemplate gridFsTemplate() throws Exception
{
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
@Override
protected String getDatabaseName()
{
return "SEaaS";
}
@Override
@Bean
public Mongo mongo() throws Exception
{
return new MongoClient("localhost" , 27017 );
}
public @Bean MongoTemplate mongoTemplate() throws Exception
{
return new MongoTemplate(mongo(), getDatabaseName());
}
}
答案 0 :(得分:4)
问题在于您没有使用Spring来获取ActorService
依赖项 - 而是使用
private ActorService actorService = new ActorService();
。
以下代码是将ActorService
依赖项注入控制器的最简单修复。
@RestController
public class Controllers
{
private static final Logger logger = Logger.getLogger(Controllers.class);
private static final ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
@Autowired
private ActorService actorService;
@RequestMapping(value="/createActor", method=RequestMethod.POST)
public @ResponseBody String createActor(@RequestParam(value = "fName") String fName,
@RequestParam(value = "lName") String lName,
@RequestParam(value = "role") String role)
{
return actorService.insert(new Actor(null,fName,lName,role)).toString();
}
...
}