目录
1.1 第一步:拷贝必备 jar 包到工程的 lib 目录。
1.2 第二步:使用@Component 注解配置管理的资源
1.3 第三步:创建 spring 的 xml 配置文件并开启对注解的支持
2.1.2 @Controller @Service @Repository
-
1 环境搭建
- 注解配置和 xml 配置要实现同样的功能都,即降低程序间的耦合,只是配置的形式不同。
- 实际的开发中依赖于使用习惯,都需要掌握。
-
1.1 第一步:拷贝必备 jar 包到工程的 lib 目录。
- 注意:在基于注解的配置中,要多拷贝一个 aop 的 jar 包。如下图:
-
1.2 第二步:使用@Component 注解配置管理的资源
- 账户的业务层实现类
-
@Component("accountService") public class AccountServiceImpl implements IAccountService { private IAccountDao accountDao; public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; } }
- 账户的持久层实现类
-
@Component("accountDao") public class AccountDaoImpl implements IAccountDao { private DBAssit dbAssit; }
- 注意:使用注解注入时,set 方法不用写
-
1.3 第三步:创建 spring 的 xml 配置文件并开启对注解的支持
- 注意:
- 基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。
- 由于使用了注解配置,此时不能在继承 JdbcDaoSupport,需要自己配置一个 JdbcTemplate
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 告知 spring 创建容器时要扫描的包 --> <context:component-scan base-package="com.itheima"></context:component-scan> <!-- 配置 dbAssit --> <bean id="dbAssit" class="com.itheima.dbassit.DBAssit"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property> <property name="user" value="root"></property> <property name="password" value="1234"></property> </bean> </beans>
-
2 常用注解
-
2.1 用于创建对象的注解
- 相当于:<bean id="" class="">
-
2.1.1 @Component
- 作用:
- 把资源让 spring 来管理。相当于在 xml 中配置一个 bean。 </
- 作用:
-