エラー内容
Spring Batchで@Mapperが付与されたインタフェースを@Autowiredしようとしたら下記エラーがでました。
エラー1
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mapper in com.example.demo.config.BatchConfig required a bean of type 'com.example.demo.mapper.TestMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.mapper.TestMapper' in your configuration.
エラー2
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'testMapper' defined in file [com\example\demo\mapper\TestMapper.class]: Invalid value type for attribute 'factoryBeanObjectType': java.lang.String
普段は呼び出される方のクラスに@Componentを忘れているのが原因のためアノテーション付与をすれば解決できるのですが、うまくいかなかったので解決した方法を残します。
エラーが発生したコード
エラー1が出たときのバージョン
build.gradle
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'
エラー2が出たときのバージョン
build.gradle
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.3.0'
gradle以外はエラー1, 2に関わらず同じコードを使用
BatchConfig.java
@Configuration
public class BatchConfig {
@Autowired
TestMapper testMapper;
...
}
TestMapper.java
@Mapper
public interface TestMapper {
@Select("select * from test")
Collection<Test> selectAll();
}
解決方法
build.gradle
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.4'
mybatisのバージョンを上げます。
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| batchConfig (field com.example.demo.mapper.TestMapper com.example.demo.config.BatchConfig.mapper)
↑ ↓
| testMapper defined in file [com\example\demo\mapper\TestMapper.class]
↑ ↓
| dataSourceScriptDatabaseInitializer defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
上記エラーが出た場合は下記対応をします。
BatchConfig.java
@Configuration
public class BatchConfig {
@Autowired
@Lazy
TestMapper mapper;
...
}
@Lazyを付与
これで解決しました。