2015-11-03 81 views
3

我正在使用SpringBoot处理Spring 4应用程序。Beancreationexception + NosuchBean定义异常

在com.test.tm包,
应用类:

@SpringBootApplication 
@EnableJpaRepositories(repositoryFactoryBeanClass = GenericRepositoryFactoryBean.class) 
@Import({ HikariDataSourceConfig.class }) 
public class Application { 
    public static void main(String[] args) 
    { 
    SpringApplication.run(Application.class, args); 
    } 
} 

在com.test.tm.entities包,
用户类别:

@Table(name = "test.user") 
@Entity 
public class User implements Serializable { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer id; 
    private String message; 
    .... 
} 

在com.test .tm.user
UserService.class:

@Service 
@Transactional(rollbackFor = Exception.class) 
public class UserService { 

@Autowired 
private GenericRepository<User, Serializable> gr; 

public User saveEntity(User usr) 
{ 
    return gr.save(usr); 
} 

public String getUser() 
{ 
    //Get User logic 
} 
} 

GenericRepository.java:

@NoRepositoryBean 
public interface GenericRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> { 
    public List<T> findByNamedQuery(String name); 
    public List<T> findByNamedQueryAndParams(String name, Map<String, Object> params); 
} 

有一个GenericRepositoryImpl.java以及其中用于上述方法的逻辑被实现。

在运行Application.java,我收到以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.utils.spring.repo.GenericRepository com.test.tm.user.UserService.gr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type[com.test.utils.spring.repo.GenericRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.Dependency annotations: {@ org.springframework.beans.factory.annotation.Autowired(required = true) } 
  1. 没有名为userService这样的变量,我定义,但它仍然显示错误。
  2. 任何方式我可以解决上述问题。
+1

对于1/SpringBoot将自动扫描Application.java所在的当前软件包(默认)并解析自动装配字段(如gr)。 –

+0

对于2 /我不知道com.test.utils.spring.repo.GenericRepository是什么,你可以将它添加到你的文章? –

+0

@alias_boubou:我添加了GenricRepository – Abhishek

回答

1

Ad。 1. Spring使用默认名称创建userService bean,如documentation中所示。

Ad。 2.我不是起诉,当然,但也许GenericRepositoryImplcom.test.tm包?如果是,则指定附加的@ComponentScan注释以及正确的包装声明。 @ComponentScan("com.test.utils"),或者 - 如果您使用Boot 1.3+ - 修改@SpringBootApplication(scanBasePackages={"com.test.utils","com.test.tm"})