mybatis / spring

Spring integration for MyBatis 3
Apache License 2.0
2.83k stars 2.6k forks source link

Support dependency injection in custom type handlers #493

Open TranNgocKhoa opened 4 years ago

TranNgocKhoa commented 4 years ago

I know there is already an issue at #218 and solution is:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- .... -->
        <property name="typeHandlers">
          <array>
            <bean class="com.example.YurCustomTypeHandler">
              <property name="aProperty" ref="aBean"/>
            </bean>
          </array>
        </property>
    </bean>

But I think bellow is better because now is 2020 and we should use Java Configuration.

public class JsonObjectArrayHandler extends BaseTypeHandler<List<Gallery>> {
    private final ObjectMapper objectMapper;

    public JsonObjectArrayHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

And then in application.yml of Spring Boot application:

mybatis:
  type-handlers-package: com.example.handler

Please add support for this. Thank you so much!

suraj092kumar commented 3 years ago

It throws error on startup It keeps asking for default constructor.

superxiao commented 1 month ago

I have successfully injected a Spring dependency into custom type handler, using @EnableSpringConfigured (on an @Configuration class) and @Configurable (on the type handler class) from org.springframework:spring-aspects. You would also need to @Autowired a field or a setter inside the type handler.

See Using AspectJ to Dependency Inject Domain Objects with Spring

Edit: AspectJ weaving is a prerequisite for this to work.