java - Which way is better while Injecting mapper interface with MyBatis-Spring -
i wondering difference between injecting mapper interface via constructor argument , via property.
code snippets in below:
via constructor argument
<bean id="mapper" class="org.mybatis.spring.mapper.mapperfactorybean"> <property name="mapperinterface" value="com.example.mybatis.somemapper"/> <property name="sqlsessionfactory" ref="sqlsessionfactory"/> </bean> <bean id="serviceimpl" class="com.example.service.someserviceimpl"> <constructor-arg ref="mapper"/> </bean>
java
public class someserviceimpl { private final somemapper mapper; public safeboxdao(somemapper mapper) { this.mapper = mapper; } }
via property
<bean id="mapper" class="org.mybatis.spring.mapper.mapperfactorybean"> <property name="mapperinterface" value="com.example.mybatis.somemapper"/> <property name="sqlsessionfactory" ref="sqlsessionfactory"/> </bean> <bean id="serviceimpl" class="com.example.service.someserviceimpl"> <property name="mapperinstance" ref="mapper" /> </bean>
java
public class someserviceimpl { private somemapper mapper; public safeboxdao() { this.mapper = mapper; } public void setmapper(somemapper mapper) { this.mapper = mapper; } }
is there difference, or different ways inject mappers?
generally speaking (i.e. not limited question) constructor injection better, given container agnostic. if move spring (unlikely in case, given dependency on spring-mybatis module) cdi, dont have worry mappers being injected correctly.
while strictly speaking in context of spring container, i'd prefer setter injection given following advice on spring docs.
the spring team advocates constructor injection enables 1 implement application components immutable objects , ensure required dependencies not null. furthermore constructor-injected components returned client (calling) code in initialized state. side note, large number of constructor arguments bad code smell, implying class has many responsibilities , should refactored better address proper separation of concerns.
Comments
Post a Comment