一、基于XML配置文件:
1.第一步:拷贝必备的jar包到工程的lib目录中
2.第二步:在类的根路径下创建的一个任意名称的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
3.第三步:让spring管理资源置,在配置文件中配置service和dao
<!-- bean标签:用于配置让spring创建对象并且存入ioc容器之中id属性:对象的唯一标识。
class 属性:指定要创建对象的全限定类名
-->
<!-- 配置 service -->
<bean id="accountService" class="XXX.XXXXX.service.impl.AccountServiceImpl">
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="XXX.XXXXX.dao.impl.AccountDaoImpl"></bean>
4.测试配置是否成功
public class Client {
/**
* 使用 main 方法获取容器测试执行
*/
public static void main(String[] args) {
//1.使用 ApplicationContext 接口,就是在获取 spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 bean 的 id 获取对象
IAccountService aService = (IAccountService) ac.getBean("accountService");
System.out.println(aService);
IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
System.out.println(aDao);
}
}
二、基于注解的IOC配置
1.第一步:拷贝必备jar包到工程的lib
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 方法不用写
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="XXX.XXXXX"></context:component-scan>
<!-- 配置 dbAssit -->
<bean id="dbAssit" class="XXX.XXXXX.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="XXX.XXXXX.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///数据库名称"></property>
<property name="user" value="#用户名#"></property>
<property name="password" value="#密码#"></property>
</bean>
</beans>
4.常用注解
1 @Component
作用:
把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
属性:
value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。
2 @Controller @Service @Repository
他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。
他们只不过是提供了更加明确的语义化。
@Controller :一般用于表现层的注解。
@Service :一般用于业务层的注解。
@Repository :一般用于持久层的注解。
细节:
如果注解中有且只有一个属性 要赋值时是 ,且名称是 value ,value
3 @Autowired
作用:
自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他 bean 类型。当有多个
类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到
就报错。
4 @Qualifier
作用:
在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;
但是给方法参数注入时,可以独立使用。
属性:
value:指定 bean 的 id。
5 @Resource
作用:
直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
属性:
name:指定 bean 的 id。
6 @Value
作用:
注入基本数据类型和 String 类型数据的
属性:
value:用于指定值
7 @Scope
作用:
指定 bean 的作用范围。
属性:
value:指定范围的值。
取值:
singleton prototype request session globalsession
8 @PostConstruct
作用:
用于指定初始化方法。
9 @PreDestroy
作用:
用于指定销毁方法。
三、使用spring的IoC的实现账户的CRUD
I.环境搭建
1.拷贝jar包
2.创建数据库和编写实体类
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
}
3.编写持久层代码
public interface IAccountDao {
/**
* 保存
* @param account
*/
void save(Account account);
/**
* 更新
* @param account
*/
void update(Account account);
/**
* 删除
* @param accountId
*/
void delete(Integer accountId);
/**
* 根据 id 查询
* @param accountId
* @return
*/
Account findById(Integer accountId);
/**
* 查询所有
* @return
*/
List<Account> findAll();
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
public void setDbAssit(DBAssit dbAssit) {
this.dbAssit = dbAssit;
}
@Override
public void save(Account account) {
dbAssit.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
}
@Override
public void update(Account account) {
dbAssit.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
@Override
public void delete(Integer accountId) {
dbAssit.update("delete from account where id=?",accountId);
}
@Override
public Account findById(Integer accountId) {
return dbAssit.query("select * from account where id=?",new BeanHandler<Account>(Account.class),accountId);
}
@Override
public List<Account> findAll() {
return dbAssit.query("select * from account where id=?",new BeanListHandler<Account>(Account.class));
}
}
4.编写业务层代码
public interface IAccountService {
/**
* 保存账户
* @param account
*/
void saveAccount(Account account);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
/**
* 删除账户
* @param account
*/
void deleteAccount(Integer accountId);
/**
* 根据 id 查询账户
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 查询所有账户
* @return
*/
List<Account> findAllAccount();
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void saveAccount(Account account) {
accountDao.save(account);
}
@Override
public void updateAccount(Account account) {
accountDao.update(account);
}
@Override
public void deleteAccount(Integer accountId) {
accountDao.delete(accountId);
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findById(accountId);
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAll();
}
}
5.创建并编写配置文件 bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
II.配置步骤
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 配置 service -->
<bean id="accountService" class="XXX.XXXXX.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="XXX.XXXXX.dao.impl.AccountDaoImpl">
<property name="dbAssit" ref="dbAssit"></property>
</bean>
<!-- 配置 dbAssit 此处我们只注入了数据源,表明每条语句独立事务-->
<bean id="dbAssit" class="XXX.XXXXX.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:///数据库名称"></property>
<property name="user" value="#用户名#"></property>
<property name="password" value="#密码#"></property>
</bean>
</beans>
III.测试案例
public class AccountServiceTest {
/**
* 测试保存
*/
@Test
public void testSaveAccount() {
Account account = new Account();
account.setName("黑马程序员");
account.setMoney(100000f);
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
as.saveAccount(account);
}
/**
* 测试查询一个
*/
@Test
public void testFindAccountById() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
Account account = as.findAccountById(1);
System.out.println(account);
}
/**
* 测试更新
*/
@Test
public void testUpdateAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
Account account = as.findAccountById(1);
account.setMoney(20301050f);
as.updateAccount(account);
}
/**
* 测试删除
*/
@Test
public void testDeleteAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
as.deleteAccount(1);
}
/**
* 测试查询所有
*/
@Test
public void testFindAllAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
List<Account> list = as.findAllAccount();
for(Account account : list) {
System.out.println(account);
}
}
}
四、IOC的配置
能够通过spring创建对象(3种)
第一种方式:使用默认构造函数创建。
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="XXX.XXXXX.service.impl.AccountServiceImpl"></bean>
第二种方式: 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
<bean id="instanceFactory" class="XXX.XXXXX.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
<bean id="accountService" class="XXX.XXXXX.factory.StaticFactory" factory-method="getAccountService"></bean>
工厂方法创建对象时,如果工厂方法有参数,使用<constructor-arg>配置参数,如下
<bean id="accountService1" factory-bean="instanceFactory" factory-method="getAccountService">
<constructor-arg name="i" value="10"></constructor-arg>
</bean>
五、DI的配置
能够对spring创建的对象里的依赖注入值
构造
set
复杂类型的注入
六、Spring整合Junit
1.第一步:拷贝整合junit的必备jar包到lib
2.第二步:使用@RunWith注解替换原有运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
3.第三步:使用@ContextConfiguration指定spring配置文件的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
△@ContextConfiguration 注解:
locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
4.第四步:使用@Autowired给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}