Spring IOC 基于xml开发
bean的配置
*<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">*
此处如果用的是idea,直接在resources目录下new中选择 XML Configuration File下 Spring Config即可自动生成
**
spring对bean的管理细节
**
1.创建bean的三种方式
2.bean对象的作用范围
3.bean对象的生命周期
配置service
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
1.1关于配置service
<!-- 第一种方式:使用默认构造函数创建。
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl"></bean>
-->
<!-- 第二种方式: 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
<bean id="instanceFactory" class="com.xxx.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
-->
<!-- 第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
<bean id="accountService" class="com.xxx.factory.StaticFactory" factory-method="getAccountService"></bean>
-->
1.2bean的作用范围调整
bean标签的scope属性:
作用:用于指定bean的作用范围
取值: 常用的就是单例的和多例的
singleton:单例的(默认值)
prototype:多例的
request:作用于web应用的请求范围
session:作用于web应用的会话范围
global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl" scope="prototype"></bean>
1.3bean的生命周期
单例对象
出生:当容器创建时对象出生
活着:只要容器还在,对象一直活着
死亡:容器销毁,对象消亡
总结:单例对象的生命周期和容器相同
多例对象
出生:当我们使用对象时spring框架为我们创建
活着:对象只要是在使用过程中就一直活着。
死亡:当对象长时间不用,且没有别的对象引用时,由Java的垃圾回收器回收
<bean id="accountService" class="com.xxx.service.impl.AccountServiceImpl"
scope="prototype" init-method="init" destroy-method="destroy"></bean>
下面就编写一个简单的案例,对上述知识进行一个运用
创建maven项目,导入相关jar包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency><!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
1 . 在数据库中新建一个account表
2.0 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">
<bean id="accountService" class="cn.bj.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<bean id="accountDao" class="cn.bj.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"></property>
</bean>
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</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://localhost:3306/account"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
2.1编写实体类
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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
2.2编写service层代码
2.2.1在AccountService中定义CRUD方法
public interface AccountService {
//查询所有
public List<Account> findAll();
//通过id查询
public Account findById(int id);
//通过id更改账户
public void updataMethod(Account account);
//通过id删除账户
public void deleteById(int id);
//通过名字模糊查询
public List<Account> findByName(String name);
//多条件查询
public List<Account> findAccount(Account account);
}
2.2.2在AccountServiceImpl中调用持久层的实现方法
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
//此处要定义持久层变量,以前需要new出来,现在交由spring来管理,只用申明,并生成相应的setting方法即可。
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findById(int id) {
return accountDao.findById( id);
}
public void updataMethod(Account account) {
accountDao.updataMethod(account);
}
public void deleteById(int id) {
accountDao.deleteById(id);
}
public List<Account> findByName(String name) {
return accountDao.findByName(name);
}
public List<Account> findAccount(Account account){
return accountDao.findAccount(account);
}
}
2.3编写持久层代码
2.3.1持久层接口代码直接复制service层代码即可
public interface AccountDao {
public List<Account> findAll();
public Account findById(int id);
public void updataMethod(Account account);
public void deleteById(int id);
public List<Account> findByName(String name);
public List<Account> findAccount(Account account);
}
2.3.2 AccountDaoImpl代码实现
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAll() {
try {
return runner.query("select * from accout_t", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findById(int id) {
try {
return runner.query("select * from accout_t where id=?", new BeanHandler<Account>(Account.class), id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updataMethod(Account account) {
try {
runner.update("update accout_t set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteById(int id) {
try{
runner.update("delete from accout_t where id=?",id);
}catch (Exception e){
throw new RuntimeException(e);
}
}
public List<Account> findByName(String name) {
try {
return runner.query("select * from accout_t where name like ?",new BeanListHandler<Account>(Account.class),'%'+name+'%');
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Account> findAccount(Account account){
try{
StringBuffer buffer = new StringBuffer("select * from accout_t where 1 = 1 ");
List<Object> params = new ArrayList<Object>();
if(account != null){
Integer id = account.getId();
System.out.println(id == null);
if(id != null){
buffer.append(" and id = ? ");
params.add(id);
}
String name = account.getName();
if (name!=null&&!"".equals(name)){
buffer.append(" and name like ?");
params.add("%"+name+"%");
}
Float money = account.getMoney();
if (money!=null && !"".equals(money)){
buffer.append(" and money = ? ");
params.add(money);
}
}
return runner.query(buffer.toString(),new BeanListHandler<Account>(Account.class),params.toArray());
}catch (Exception e){
throw new RuntimeException(e);
}
}
3.测试类
public class AccountTest {
private AccountService service;
@Before
public void init(){
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
service = ac.getBean("accountService", AccountService.class);
}
@Test
/**
* 查询所有
*/
public void findAll() {
List<Account> all = service.findAll();
System.out.println(all);
}
@Test
/**
* 根据id查询
*/
public void findById() {
Account byId = service.findById(2);
System.out.println(byId);
}
@Test
/**
* 更新表
*/
public void updataAccount() {
Account account=new Account();
account.setMoney(1233F);
account.setName("sasd");
account.setId(1);
service.updataMethod(account);
}
@Test
/**
* 删除表
*/
public void deleteAccount() {
service.deleteById(1);
}
@Test
public void testFindByName(){
List<Account> accounts = service.findByName("bbb");
System.out.println(accounts);
}
@Test
public void testCondition(){
Account acc = new Account();
List<Account> account = service.findAccount(acc);
System.out.println(account);
}
}