如何将Class <t>注入bean?

时间:2017-01-02 07:42:52

标签: java spring spring-boot spring-data

我有以下类UserAuthorityRepository作为存储库:

@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.

2 个答案:

答案 0 :(得分: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);
   }

}

答案 1 :(得分:0)

您是否尝试过使用@Configuration

@Configuration
public class InjectConfiguration {

    @Bean("providerEmployeeContext")
    @RequestScope
    public IEmployeeContext<Employee> providerEmployeeConfiguration() {

        return new EmployeeContext<>(sessionFactory(), Employee.class);
    }

}