web-dev-qa-db-ja.com

依存ライブラリjarに存在するBeanを@Autowireできないのですか?

私は、Spring Bootアプリケーション(Y)を持っています。これは、x.jarとしてパックされ、アプリケーションYのpom.xmlで依存関係として言及されている一連のライブラリファイルに依存しています。

x.jarには(User.Java)という名前のBeanがあり、アプリケーションYにはJavaという名前の(Department.Java)というクラスがあります。

Department.Java内のUser.JavaのインスタンスをAutowireしようとすると、次のエラーが発生します

依存ライブラリjarに存在するBeanを@Autowireできませんか?

フィールドを自動配線できませんでした:プライベートcom.Userユーザー;ネストされた例外はorg.springframework.beans.factory.NoSuchBeanDefinitionException:タイプ[com.User]の適格Beanが依存関係に見つかりません:この依存関係のautowire候補として適格な少なくとも1つのBeanが必要です。依存関係アノテーション:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

タイプ[com.User]の適格なBeanが依存関係に見つかりません:この依存関係のautowire候補として適格な少なくとも1つのBeanが必要です。依存関係アノテーション:{@ org.springframework.beans.factory.annotation.Autowired(required = true)} **

これがSpring Boot Application 'Y'のコードです

package myapp;

@Component
public class Department {

    @Autowired
    private com.User user;

    //has getter setters for user

}

これは、ライブラリx.jar内のUser.Javaのコードです。

 package com;

@Component
@ConfigurationProperties(prefix = "test.userproperties")
public class User {

  private String name;
  //has getter setters for name    
}

これは、アプリケーションYのpom.xml内のx.jarの依存関係エントリです。

      <groupId>com.Lib</groupId>
      <artifactId>x</artifactId>
      <version>001</version>
    </dependency>   

これはアプリケーション「Y」のメインクラスです

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableZuulProxy
@EnableGemfireSession(maxInactiveIntervalInSeconds=60)
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableDiscoveryClient
public class ZuulApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ZuulApplication.class).web(true).run(args);
    }
}   

部門とユーザーの両方が異なるパッケージの下にあります。

解決策:次の2つのステップを適用したところ、自動配線は正常に機能しています。

ステップ1:次のクラスをjarファイルに追加しました

package com
@Configuration
@ComponentScan
public class XConfiguration {

}

ステップ2:Yプロジェクトのメインクラスにこの構成クラスをインポートしました

@Configuration
    @EnableAutoConfiguration
    @ComponentScan
    @EnableZuulProxy
    @EnableGemfireSession(maxInactiveIntervalInSeconds=60)
    @EnableCircuitBreaker
    @EnableHystrixDashboard
    @EnableDiscoveryClient
    @Import(XConfiguration.class) 
    public class ZuulApplication {

        public static void main(String[] args) {
            new SpringApplicationBuilder(ZuulApplication.class).web(true).run(args);
        }
    }
15
yathirigan

100%確実にするには、メインクラスとユーザークラスのパッケージ名を追加する必要がありますが、ほとんどの場合、ユーザークラスはメインクラスの同じパッケージ(またはサブパッケージ)にありません。これは、コンポーネントのスキャンでは検出されないことを意味します。

Springに次のような他のパッケージを表示させることができます。

@ComponentScan(basePackages = {"org.example.main", "package.of.user.class"})
12
Wim Deblauwe