Spring框架中bean配置

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);
}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值