Spring 引导将 CrudRepository 注入服务
Spring Boot Inject CrudRepository into Service
我很难将 CrudRepository 注入到使用 @Service 注释进行注释的服务中。我有两个包,一个 "core" 包含@Service 定义和可重用控制器定义的包。
我在x.y.application包中的主要应用如下:
package x.y.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({ "x.y.application", "x.y.core" })
public class Application {
public static void main( String[] args ) {
SpringApplication.run( Application.class, args );
}
}
然后是控制器示例。
package x.y.application.controller;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import x.y.application.model.User;
import x.y.core.controller.Controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.repository.CrudRepository;
@RestController
@RequestMapping("/test")
public class HelloController extends Controller<User> {
}
然后我的可重用控制器class
package x.y.core.controller;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.beans.factory.annotation.Autowired;
import x.y.core.service.Service;
public class Controller<T> {
@Inject
Service<T> service;
@RequestMapping(value = "/index.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public T create( @RequestBody T item ) throws Exception {
return service.create( item );
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public T update( @PathVariable Long id, @RequestBody T item ) throws Exception {
return service.update( item );
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public T read( @PathVariable Long id ) throws Exception {
return service.findOne( id );
}
@RequestMapping(value = "/index.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<T> readAll() throws Exception {
return service.findAll();
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete( @PathVariable Long id ) throws Exception {
service.delete( id );
}
}
然后是我的服务界面
package x.y.core.service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.lang.reflect.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
public interface Service<T> {
/**
* create.
* Creates a new entity in the database.
*/
public T create( T item );
/**
* update.
* Updates an existing entity in the database.
*/
public T update( T item );
public T findOne( Long id );
public List<T> findAll();
public void delete( Long id );
}
最后是有问题的服务实现。
package x.y.core.service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.lang.reflect.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Service
public class RepositoryService<T> implements Service<T> {
@Inject //Throws exception
CrudRepository<T,Long> repository;
/**
* create.
* Creates a new entity in the database.
*/
public T create( T item ) throws DataIntegrityViolationException {
/*try {
Field field = item.getClass().getDeclaredField( "id" );
field.setAccessible( true );
if( repository.exists( field.getLong( item ) ) ) {
throw new DataIntegrityViolationException( "Entity object already exists." );
}
} catch ( Exception exception ) {
throw new DataIntegrityViolationException( "Entity class does not contain Id attribute." );
}
return repository.save( item );*/ return item;
}
/**
* update.
* Updates an existing entity in the database.
*/
public T update( T item ) throws DataIntegrityViolationException {
/*try {
Field field = item.getClass().getDeclaredField( "id" );
field.setAccessible( true );
if( !repository.exists( field.getLong( item ) ) ) {
throw new DataIntegrityViolationException( "Entity object does not exists." );
}
} catch ( Exception exception ) {
throw new DataIntegrityViolationException( "Entity class does not contain Id attribute." );
}
return repository.save( item );*/ return item;
}
public T findOne( Long id ) {
/*if( !repository.exists( id ) ) {
throw new DataIntegrityViolationException( "Item with id does not exists." );
}
return repository.findOne( id );*/ return null;
}
public List<T> findAll() {
final List<T> resultList = new ArrayList<>();
/*/ final Iterator<T> all = repository.findAll().iterator();
while( all.hasNext() ) {
resultList.add( all.next() );
}*/
return resultList;
}
public void delete( Long id ) {
/*if( !repository.exists( id ) ) {
throw new DataIntegrityViolationException( "Item with id does not exists." );
}
repository.delete( id );*/
}
}
异常
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.repository.CrudRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
似乎任何spring注册的Component、Service、Resource都不能注入CrudRepository?
但是,如果我不在 x.y.application 包中注释 CrudRepository,它会编译并注入 CrudRepository?
这可能是因为 CrudRepository 不是包扫描的一部分。因此 spring 无法为其注入代理实现。
要使依赖注入起作用,应用程序上下文必须知道创建特定 class 实例的方法。 类 其实例创建配方已知被称为 "beans"。您可以通过 XML 配置文件(旧学校)或注释(新学校)定义 bean。
您收到的错误消息表明应用程序上下文没有 CrudRepository bean,即它不知道如何创建 class 的实例实现此接口。
要以新的方式创建 bean 定义,您可以注释一个 class 或一个特定的方法,其中 return 特定 class 的实例与 @Bean 或包含它的任何其他元注释(@Service、@Controller 等)。
如果您打算使用 Spring 项目数据套件来自动生成存储库实现,您需要注释一个扩展核心 Spring 数据接口之一的接口(Repository、CrudRepository、PagingAndSortingRepository ) 带有 @Repository 注释,像这样
@Repository
public interface MyRepository extends CrudRepository<Entity, Long> {
}
这为应用程序上下文提供了一个 bean 定义,并使其知道您希望为您生成存储库实现。
然后你可以注入 MyRepository 到服务 class.
我唯一的疑问是要在存储库类型定义中使用的通用类型。我希望存储库实现(您希望为您生成的那个)是特定于实体的而不是抽象的。
我很难将 CrudRepository 注入到使用 @Service 注释进行注释的服务中。我有两个包,一个 "core" 包含@Service 定义和可重用控制器定义的包。
我在x.y.application包中的主要应用如下:
package x.y.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({ "x.y.application", "x.y.core" })
public class Application {
public static void main( String[] args ) {
SpringApplication.run( Application.class, args );
}
}
然后是控制器示例。
package x.y.application.controller;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import x.y.application.model.User;
import x.y.core.controller.Controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.repository.CrudRepository;
@RestController
@RequestMapping("/test")
public class HelloController extends Controller<User> {
}
然后我的可重用控制器class
package x.y.core.controller;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.beans.factory.annotation.Autowired;
import x.y.core.service.Service;
public class Controller<T> {
@Inject
Service<T> service;
@RequestMapping(value = "/index.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public T create( @RequestBody T item ) throws Exception {
return service.create( item );
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public T update( @PathVariable Long id, @RequestBody T item ) throws Exception {
return service.update( item );
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public T read( @PathVariable Long id ) throws Exception {
return service.findOne( id );
}
@RequestMapping(value = "/index.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<T> readAll() throws Exception {
return service.findAll();
}
@RequestMapping(value = "/{id}.json", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete( @PathVariable Long id ) throws Exception {
service.delete( id );
}
}
然后是我的服务界面
package x.y.core.service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.lang.reflect.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
public interface Service<T> {
/**
* create.
* Creates a new entity in the database.
*/
public T create( T item );
/**
* update.
* Updates an existing entity in the database.
*/
public T update( T item );
public T findOne( Long id );
public List<T> findAll();
public void delete( Long id );
}
最后是有问题的服务实现。
package x.y.core.service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.lang.reflect.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.http.HttpStatus;
import org.springframework.data.repository.CrudRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Service
public class RepositoryService<T> implements Service<T> {
@Inject //Throws exception
CrudRepository<T,Long> repository;
/**
* create.
* Creates a new entity in the database.
*/
public T create( T item ) throws DataIntegrityViolationException {
/*try {
Field field = item.getClass().getDeclaredField( "id" );
field.setAccessible( true );
if( repository.exists( field.getLong( item ) ) ) {
throw new DataIntegrityViolationException( "Entity object already exists." );
}
} catch ( Exception exception ) {
throw new DataIntegrityViolationException( "Entity class does not contain Id attribute." );
}
return repository.save( item );*/ return item;
}
/**
* update.
* Updates an existing entity in the database.
*/
public T update( T item ) throws DataIntegrityViolationException {
/*try {
Field field = item.getClass().getDeclaredField( "id" );
field.setAccessible( true );
if( !repository.exists( field.getLong( item ) ) ) {
throw new DataIntegrityViolationException( "Entity object does not exists." );
}
} catch ( Exception exception ) {
throw new DataIntegrityViolationException( "Entity class does not contain Id attribute." );
}
return repository.save( item );*/ return item;
}
public T findOne( Long id ) {
/*if( !repository.exists( id ) ) {
throw new DataIntegrityViolationException( "Item with id does not exists." );
}
return repository.findOne( id );*/ return null;
}
public List<T> findAll() {
final List<T> resultList = new ArrayList<>();
/*/ final Iterator<T> all = repository.findAll().iterator();
while( all.hasNext() ) {
resultList.add( all.next() );
}*/
return resultList;
}
public void delete( Long id ) {
/*if( !repository.exists( id ) ) {
throw new DataIntegrityViolationException( "Item with id does not exists." );
}
repository.delete( id );*/
}
}
异常
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.repository.CrudRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
似乎任何spring注册的Component、Service、Resource都不能注入CrudRepository? 但是,如果我不在 x.y.application 包中注释 CrudRepository,它会编译并注入 CrudRepository?
这可能是因为 CrudRepository 不是包扫描的一部分。因此 spring 无法为其注入代理实现。
要使依赖注入起作用,应用程序上下文必须知道创建特定 class 实例的方法。 类 其实例创建配方已知被称为 "beans"。您可以通过 XML 配置文件(旧学校)或注释(新学校)定义 bean。
您收到的错误消息表明应用程序上下文没有 CrudRepository bean,即它不知道如何创建 class 的实例实现此接口。
要以新的方式创建 bean 定义,您可以注释一个 class 或一个特定的方法,其中 return 特定 class 的实例与 @Bean 或包含它的任何其他元注释(@Service、@Controller 等)。
如果您打算使用 Spring 项目数据套件来自动生成存储库实现,您需要注释一个扩展核心 Spring 数据接口之一的接口(Repository、CrudRepository、PagingAndSortingRepository ) 带有 @Repository 注释,像这样
@Repository
public interface MyRepository extends CrudRepository<Entity, Long> {
}
这为应用程序上下文提供了一个 bean 定义,并使其知道您希望为您生成存储库实现。
然后你可以注入 MyRepository 到服务 class.
我唯一的疑问是要在存储库类型定义中使用的通用类型。我希望存储库实现(您希望为您生成的那个)是特定于实体的而不是抽象的。