Spring 引导构造函数自动装配异常

Spring boot Constructor Autowired Exception

我的 spring 引导应用程序中有这个 classes(spring hibernate/data/jpa/web):

pkg 实体:

public interface Base {
// getter/setter methods
}

@MappedSuperclass
public abstract class AbsBase implements Base {
// common fields & getter/setter methods
}

@Entity(name = "Config")
@Table(name = "config")
public class Config extends AbsBase implements Base, Serializable {
  //additional fields & getter/setter methods
}

pkg 存储库:

@NoRepositoryBean
public interface BaseRepository<T extends Base> extends JpaRepository<T, Integer> {}

@Repository
public interface ConfigRepository extends BaseRepository<Config> {
//Queries
}

pkg 服务:

@Transactional
public interface BaseService<T extends Base> {

    @Transactional  void add(T obj);
    @Transactional  void edit(T obj);
    //Etc..
}

public abstract class AbsBaseService<T extends Base> implements BaseService<T> {

    private BaseRepository<T> repository;

    public AbsBaseService(BaseRepository<T> repository) {
        super();
        this.repository = repository;
    }

    @Override   public void add(T obj) { repository.save(obj); }
    @Override   public void edit(T obj) { repository.save(obj); }
    // Etc
}

@Service
public class ConfigService extends AbsBaseService<Config> implements BaseService<Config> {

    private ConfigRepository repository;

    @Autowired
    public ConfigService(ConfigRepository repository) {
        super(repository);
        this.repository = repository;
    }
    // Etc.
}

如果我不创建任何控制器,一切正常,但如果我创建一个控制器:

pkg 控制器:

public interface BaseController<T extends Base> { // methods }

public abstract class AbsBaseController<T extends Base> implements BaseController<T> {

    private BaseService<T> service;

    public AbsBaseController(BaseService<T> service) {
        this.service = service;
    }

@Override
@RequestMapping(value = "/Add", method = RequestMethod.POST)
public String addAction(@ModelAttribute("entity") T entity, BindingResult result, Model model,
        final RedirectAttributes redirectAttributes) {

    service.add(entity, result);
    if (result.hasErrors()) {
        return addUrl;
    }
}

@Controller
public class ConfigController extends AbsBaseController<Config> implements BaseController<Config> {

    private ConfigService configService;

    @Autowired
    public ConfigController(ConfigService configService) {
        super(configService);
        this.configService = configService;
    }
}

我收到此错误(在 ConfigController 中自动装配 ConfigService 时出错):

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configControllerImpl' defined in file [C:\workspace-sts\prueba_boot_thymeleaf\target\classes\prueba\controller\config\ConfigControllerImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [prueba.service.config.ConfigServiceImpl]: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
    at prueba.BootThymeleafApplication.main(BootThymeleafApplication.java:12) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [prueba.service.config.ConfigServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    ... 19 common frames omitted

第一个问题是: 我已经在 BaseService 接口及其方法上标注了@Transaction。这是正确的?在 AbsBaseService 中更好 class?

我看到 configService 构造函数在 Exception 之前执行。 为什么不自动装配?


更新

我需要构造函数@Autowired,因为我在abstract/superclass泛型service/controller.

中实现了常用方法

继承树: AbsBaseXXXX --> AbsBaseCodeNameXXXX --> AbsBaseCodeNamePeriodXXXX

Config 从 AbsBase 扩展并实现了 Base。 ConfigService 扩展自 AbsBaseService<> 并实现 BaseService<>(使用 ConfigRepository) ConfigController 扩展自 AbsBaseController<> 并实现 BaseController<>(使用 ConfigService)

我有通用方法实现的通用抽象 classes: 实体接口: 基础、基础代码名称、基础代码名称周期....

首先,你们中的大部分代码都可以简化,至少可以测试它是否运行良好:

@Transactional
public interface BaseService<T extends Base> {

    void add(T obj); // No need to repeat @Transactional here, unless you want to override default behaviour (says, read_only, for instance)
    void edit(T obj);
    //Etc..
}

// Not much use of an Abstract class here, all methods are exposed in the interface already

@Service
public class ConfigService implements BaseService<Config> {

    // Autowire the field directly. Constructor not needed anymore in this case
    @Autowired
    private ConfigRepository repository;
    // Etc.
}

控制器将遵循与服务相同的准则。

现在应该可以正常工作了。如果没有,您需要使用完整的堆栈跟踪(或至少是最后一个 caused by 块,这是真正有意义的块)来更新您的问题。

解决方法:

创建服务接口: IConfigService 扩展 BaseService

更改服务class: ConfigService 扩展 AbsBaseService 实现 IConfigService

在 ControllerConfig 中将 ConfigService 替换为 IConfigService

如果我使用接口工作但如果我使用 class 不工作。我不明白为什么,但它有效。

根据 https://drive.google.com/open?id=0B4DUWMYsjWtdVVRibDFZOVhac2s 上发布的代码,我现在很清楚您要实现的目标。

您想创建一个 classes(例如服务)的层次结构,在每个级别定义一些功能。例如:

  • RepoA 定义了一个 methodA 方法。
  • RepoB 扩展 RepoA 和 定义了一个 methodB 方法。
  • ServiceA 使用 RepoA class 来 公开此方法
  • ServiceB 扩展 ServiceA 并公开其 方法和 ServiceA 方法
  • 等等...

调试您的应用程序时,我发现 Spring 在调用此代码时尝试创建一个新的 AccountService bean,而不是使用现有 bean:

@Controller
@RequestMapping("/Account")
public class AccountController extends AbsBaseDataController<Account> {

    private AccountService service;

    @Autowired
    public AccountController(AccountService service) {
        super(service);
        this.service = service;
        System.out.println("AccountController-CONSTRUCTOR");
    }
}

这是因为您直接使用 AccountService class,而不是接口。这就是这里的重点,因为 Spring 围绕您的 classes 创建了一个代理,以便能够在它们上使用 AOP。所以当涉及到自动装配时,classes 不匹配(你认为你的 class 的一个实例被注入,但实际上这是一个 com.sun.proxy.Proxy)。

因为那些 Java 代理实现了你的 classes 的接口,你应该为你的 AccountService(比如 IAccountService)创建一个接口,并使用它而不是AccountController class' 构造函数中的原始 AccountService class:

界面

public interface IAccountService extends BaseDataService<Account> {
}

控制器

@Controller
@RequestMapping("/Account")
public class AccountController extends AbsBaseDataController<Account> {

    private IAccountService service;

    @Autowired
    public AccountController(IAccountService service) {
        super(service);
        this.service = service;
        System.out.println("AccountController-CONSTRUCTOR");
    }
}

服务class

@Service
public class AccountService extends AbsBaseDataService<Account> implements IAccountService {
[...]
}