使用FactoryBean创建GenericService Bean

时间:2016-03-06 01:20:17

标签: java spring

我使用FactoryBean为我的通用服务创建了Beans。

服务:

public abstract class SimpleServiceImpl<T extends IdEntity>
        implements SimpleService<T> {

    @Autowired
    SimpleRepository<T> entitiesRepository;

    ...

厂:

@Component
public class ServiceFactoryBean<E extends IdEntity> extends ServiceAbstractFactoryBean<E> {

        @Override
        protected SimpleServiceImpl<E> doCreateInstance() {
            return new SimpleServiceImpl<E>() { };
        }

        @Override
        public Class<?> getObjectType() {
            return SimpleService.class;
        }
    }

如果我用这个工厂创建bean,那么SimpleRepository<T> entitiesRepository; eqally SimpleRepostirory<IdEntity>而不是T类,我做错了什么?

示例使用工厂:

@RestController
@RequestMapping("/users")
public class UserController extends SimpleController<User> {
    @Autowired
    public UserController(ServiceFactoryBean<User> serviceFactoryBean) throws Exception {
        super(serviceFactoryBean.getObject());
    }
}

如果我将T替换为User中的ServiceFactoryBean,则可以正常使用

@Component
public class ServiceFactoryBean<> extends ServiceAbstractFactoryBean<User> {

    @Override
    protected SimpleServiceImpl<User> doCreateInstance() {
        return new SimpleServiceImpl<User>() { };

    }

    @Override
    public Class<?> getObjectType() {
        return SimpleService.class;
    }
}

0 个答案:

没有答案