2017-01-02 57 views
0

我有以下類UserAuthorityRepository作爲倉庫:如何將類<T>注入bean?

@Repository 
public class UserAuthorityRepository extends BaseRepository<UserAuthority, Long> implements IUserAuthorityRepository { 

public UserAuthorityRepository(Class<UserAuthority> domainClass, EntityManager em) { 
    super(domainClass, em); 
} 

} 

而在UserAuthorityService我:

@Service 
public class UserAuthorityService extends BaseService<UserAuthority, Long> implements IUserAuthorityService { 

private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthorityService.class); 

@Autowired 
private IUserAuthorityRepository userAuthorityRepo; 

public UserAuthorityService() { 
    super(); 
    LOGGER.info("UserAuthorityService Has Been Created"); 
} 

@Bean 
@Override 
public Class<UserAuthority> getDomain() { 
    return UserAuthority.class; 
} 

@Override 
public IBaseRepository<UserAuthority, Long> getRepository() { 
    return userAuthorityRepo; 
} 

} 

但我的應用程序在啓動時變得異常如下:

*************************** 
APPLICATION FAILED TO START 
*************************** 

Description: 

Parameter 0 of constructor in com.bia2hd.dao.impl.UserAuthorityRepository required a bean of type 'java.lang.Class' that could not be found. 


Action: 

Consider defining a bean of type 'java.lang.Class' in your configuration. 
+0

的可能的複製[如何設置類值的Spring bean屬性?](http://stackoverflow.com/questions/5834311/how-to-set-class-值到彈簧bean屬性) –

+0

@JoeC謝謝,但我沒有XML配置,這是所有註釋。 – Khodabakhsh

+0

所以這裏可能很愚蠢的問題......但爲什麼你需要在這種情況下注入'Class'?你的構造函數參數的唯一合法值是UserAuthority.class,那麼爲什麼不在你的superconstructor調用中明確地設置它,而不是依賴它被注入(然後只有'EntityManager'需要被注入)? –

回答

0

我只是解決了它(不太令人愉快,但工作)。

@Configuration 
public class Beans { 

    @Autowired 
    private ApplicationContext applicationContext; 

    @PostConstruct 
    public void createClassBeans() throws ClassNotFoundException { 

     ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 

     scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class)); 

     ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext) 
      .getBeanFactory(); 

     for (BeanDefinition bd : scanner.findCandidateComponents("my.package")) { 
     Class<?> bean = Class.forName(bd.getBeanClassName()); 
     beanFactory.registerSingleton(bean.getName(), bean); 
     } 

    } 

} 

而且

@Repository 
public class UserRepository extends BaseRepository<User, Long> implements IUserRepository { 

    UserRepository(@Qualifier("my.package.User") Class<User> domainClass, EntityManager em) { 
     super(domainClass, em); 
    } 

} 
相關問題