基于xml的ioc案例以及注解ioc案例


xml的ioc案例


1.环境搭建pom.xml

<packaging>jar</packaging>

<dependencies>
    <!--spring坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

	 <!--封装了JDBC的代码,简化dao层的操作-->
	   <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        
    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>

    <!--c3p0连接池-->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2.创建sql

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

3.创建domain.Account实体类

/**
 * 账户实体类
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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;
    }
}

4.创建IAccountService, AccountServiceImpl

  /**
     * 账户的业务层接口
     */
    public interface IAccountService {
    
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
    
        /**
         * 查询一个
         * @return
         */
        Account findById(Integer accountId);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
    
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
    
    
        /**
         *删除
         * @param accountId
         */
        void deleteAccount(Integer accountId);
        }
    
    
    
    
 /**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findById(Integer accountId) {
        return accountDao.findById(accountId);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }

5创建.IAccountDao accountDaoImpl

 /**
     * 账户持久层接口
     */
    public interface IAccountDao {
        /**
         * 查询所有
         * @return
         */
        List<Account> findAllAccount();
    
    
        /**
         * 查询一个
         * @return
         */
        Account findById(Integer accountId);
    
        /**
         * 保存操作
         * @param account
         */
        void saveAccount(Account account);
    
    
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
    
    
        /**
         *删除
         * @param accountId
         */
        void deleteAccount(Integer accountId);
    }





/**
 * 账户持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {
     //封装了JDBC的代码,简化dao层的操作
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    public Account findById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ? ", new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
          runner.update("insert into account(name,money) values(?,?)", account.getName(),account.getMoney());
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account set name = ?, money = ? where id = ?", account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

6.搭建spring的开发环境
在resource下创建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">

    <!-- 配置service对象-->
    <bean id="accountService" class="sise.cn.service.Impl.AccountServiceImpl">
        <!--注入dao set方法注入 其他bean类型注入-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>


    <!--配置dao对象-->
    <bean id="accountDao" class="sise.cn.dao.Impl.AccountDaoImpl">
        <!--注入QueryRunner set方式注入 其他bean类型注入 -->
        <property name="runner" ref="runner"></property>
    </bean>


    <!--配置QueryRunner对象 单例对象,可能这个用完其他在用会造成线程安全问题 所以要配scope="prototype",保证每次使用这个对象时都是创建一个新的-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源 构造函数注入 其他bean类型注入-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>


    <!--配置数据源c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入连接数据库的必备信息 set方法注入 基本类型和String注入-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc://mysql://localhost:3306/eesyioc"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>


</beans>

7.test:使用junit测试 (并不关注)

/**
 * s使用junit单元测试:测试配置
 */
public class AccountServiceTest {

    @Test
    public void testFindAll() {
        //1.获取容器对象
        ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = cs.getBean("accountService",IAccountService.class);
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //1.获取容器对象
        ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = cs.getBean("accountService",IAccountService.class);
        //3.执行方法
        Account account = as.findById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setMoney(12345f);
        account.setName("6ms");

        //1.获取容器对象
        ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = cs.getBean("accountService",IAccountService.class);
        //3.执行方法
        as.saveAccount(account);
    }


    @Test
    public void testUpdate() {
        //1.获取容器对象
        ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = cs.getBean("accountService",IAccountService.class);
        //3.执行方法
        Account account = as.findById(4);
        account.setMoney(23456f);
        as.updateAccount(account);

    }


    @Test
    public void testDelete() {
        //1.获取容器对象
        ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = cs.getBean("accountService",IAccountService.class);
        //3.执行方法
        as.deleteAccount(4);
    }
}

要点:
1.能不能看出来QueryRunner也需要注入
2.注入QueryRunner时数据源dataSource也可以实现配置并且把连接数据库的信息注入进来
3.能不能看出来QueryRunner如果是单例对象,面临多个dao使用时会产生线程安全问题


注解ioc案例


在xml的基础上改进
1.导入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"
       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="sise.cn"></context:component-scan>
    
    <!--配置QueryRunner对象 单例对象,可能这个用完其他在用会造成线程问题 所以要配scope="prototype",保证每次使用这个对象时都是创建一个新的-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源 构造函数注入 其他bean类型注入-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>


    <!--配置数据源c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入连接数据库的必备信息 set方法注入 基本类型和String注入-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesyioc"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>


</beans>

2.在AccountServiceImpl里实现把其加入spring容器中的注解

    /**
 /**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired//当用注解实现自动注入时set方法就不是必须的了
    private IAccountDao accountDao;

3.AccountDaoImpl

/**
 * 账户持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
     //封装了JDBC的代码,简化dao层的操作
    
    @Autowired//当用注解实现自动注入时set方法就不是必须的了 
    private QueryRunner runner;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、Spring配置文件 Spring配置文件是Spring框架中非常重要的一部分,它通常以XML格式编写,用于配置Spring应用程序中的各种组件,例如Bean、AOP、数据源、事务等。 在Spring配置文件中,最常用的标签是<bean>标签,用于定义和配置Spring IoC容器中的Bean对象。除此之外,还有<import>标签,用于引入其他配置文件;<aop:config>标签,用于配置AOP相关的切面和通知等;<tx:advice>标签,用于配置事务管理相关的通知等。 Spring配置文件的编写需要遵守一定的规范和约束条件,例如必须指定命名空间、必须定义命名空间的schema等。同时,Spring还提供了多种加载配置文件的方式,例如ClassPathXmlApplicationContext、FileSystemXmlApplicationContext等。 2、Spring IoC基于注解的操作和案例 除了使用XML配置文件之外,Spring IoC容器还支持基于注解的Bean定义和注入操作。在Spring中,使用注解可以大大简化配置文件的编写,提高开发效率和可读性。 常用的Spring注解包括: - @Component:用于标识一个组件,通常与@Autowired等注解一起使用。 - @Autowired:用于自动注入一个Bean对象。 - @Qualifier:用于指定一个Bean对象的名称。 - @Value:用于注入一个基本类型或String类型的属性值。 - @Configuration:用于标识一个配置类,通常与@Bean等注解一起使用。 - @Bean:用于定义一个Bean对象,通常用于@Configuration类中。 - @Profile:用于指定一个Bean对象的环境依赖。 下面是一个基于注解的Spring IoC配置案例: ``` @Configuration public class AppConfig { @Bean public UserService userService() { return new UserServiceImpl(); } } ``` 在这个案例中,使用@Configuration注解表示这是一个配置类,使用@Bean注解表示定义了一个名为“userService”的Bean对象。该Bean对象的类型是UserServiceImpl。 另外,还可以使用@Autowired和@Qualifier注解来实现Bean的自动注入。例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired @Qualifier("userRepository") private UserRepository userRepository; // ... } ``` 在这个案例中,使用@Service注解表示这是一个服务类,使用@Autowired注解表示自动注入一个名为“userRepository”的Bean对象。其中,@Qualifier注解用于指定Bean对象的名称。 总之,Spring配置文件和基于注解的操作是Spring框架中非常重要和常用的组件,它们为Java开发人员提供了一种高效、灵活和可维护的方式来管理对象和依赖关系。通过基于注解的方式,可以大大简化配置文件的编写工作,提高开发效率和可读性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值