springmvc 基于注解的注入,都不需要独立的配置文件,只需要配置扫描和增加@Autowired注解就可以,但是似乎只对controller和service的起作用。
对于dao层的话,如果只是使用@Autowired,是无法正常注入的,目前使用的方法是增加了一个独立的xxx-dao.xml,路径配置在web.xml中,不是很明白为何controll和service可以正常注入,是否是dao也需要加上@注解,类似于@controller 和@service
你可以使用ctrl + H全局搜索一下关键字:<context:component-scan。比如项目中,配置文件配置了如下语句:
<context:component-scan base-package="com.alibaba.tboss.biz" />
默认会去扫描包com.alibaba.tboss.biz下的所有java类,完成自动注入。
一般这样的配置都会配置在datasource.xml文件中,在该配置文件中,常配置以下项:
1.<context:component-scan 扫描,完成自动注入。
2.<aop:config>切面,配置事务,常配置到*ServiceImpl.java中,
3.<context:annotation-config 事务的回滚方式
如下,就是datasource.xml的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName">
<bean id="dataSource" class="com.taobao.tddl.jdbc.group.TGroupDataSource" init-method="init">
<property name="appName" value="${db_appname}"/>
<property name="dbGroupKey" value="${db_groupkey}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath*:com/**/dal/**/*Mapper*.xml" />
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.alibaba.***.dal" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="javax.annotation.Resource"></property>
<property name="basePackage" value="com.alibaba.***.dal.***.mapper,com.alibaba.***.dal.***.***.mapper" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config />
<tx:advice id="defaultTxAdvice">
<tx:attributes>
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="ao_bo"
expression="(execution(* *..*BoImpl.*(..))) or ( execution(* *..*AoImpl.*(..)) and ( not execution(* *..*AoImpl.mtx_*(..)) ) )" />
<aop:advisor pointcut-ref="ao_bo" advice-ref="defaultTxAdvice" />
</aop:config>
<context:component-scan base-package="com.alibaba.tboss.biz" />
</beans>