spring入门01

spring

1. 模拟spring

通过读取配置文件properties 将对象注入到容器中,模拟三层访问

controller

package com.itheima.ui;

import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

public class Client {

    public static void main(String[] args){
        IAccountService is =(IAccountService)BeanFactory.getBean("IAccountService");//双引号填写的是bean中等号左边值
        is.saveAccount();//向下找到实现类
    }
}

serviceImpl

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

public class AccountServiceImpl implements IAccountService {
    //IAccountDao id = new AccountDaoImpl();
   // IAccountDao id =(IAccountDao)BeanFactory.getBean("accountDao");
    public void saveAccount() {
        //利用工厂类生存对象 访问dao层
        IAccountDao id =(IAccountDao)BeanFactory.getBean("accountDao");
        id.saveAccount();
    }
}

AccountDaoImpl

package com.itheima.dao.impl;
import com.itheima.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
    @Override
    public void saveAccount() {
        //模拟访问数据库
        System.out.println("账户已经保存");
    }
}

spring的作用就是类似BeanFactory作用生成对象 即容器

BeanFactory

package com.itheima.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class BeanFactory {
    //自己构建一个生产JavaBean的工厂
    /**
     *
     *   它就是创建我们的service和dao对象的。
     *
     *   第一个:需要一个配置文件来配置我们的service和dao
     *           配置的内容:唯一标识=全限定类名(key=value)
     *   第二个:通过读取配置文件中配置的内容,反射创建对象
     *
     *   我的配置文件可以是xml也可以是properties
     */
     //读取properties文件 util包下的
    private static Properties props;
    //定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
    private  static Map<String,Object> beans;
    //使用静态代码块为Properties对象赋值
    static{
        try{
        //实例化对象
        props = new Properties();
        //获取properties文件的流对象
        InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        props.load(in);
        //实例化容器
            beans = new HashMap<String,Object>();
            //取出配置文件中所有的Key
            Enumeration keys = props.keys();
            while(keys.hasMoreElements()){
                //取出每个Key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //System.out.println(beanPath);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //放入容器
                beans.put(key,value);
//               System.out.println("key是"+key);
//                System.out.println("对象是"+value.toString());
//
        }

        }catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
//        Set<String> ke=beans.keySet();
//        for(String k : ke){
//            System.out.println(beans.get(k));
//        }
    }

    public static Object getBean(String beanName){
       return beans.get(beanName);
    }
}

bean.properties

IAccountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl

2. spring注解方式实现

spring有两种方式实现 一种是注解另一种是配置文件xml

package com.itheima.ui;

import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args){
       // IAccountService is = new AccountServiceImpl();
        //获取核心容器
        ApplicationContext beans = new ClassPathXmlApplicationContext("bean.xml");
        //取对象
        IAccountService as = (AccountServiceImpl)beans.getBean("acountService");
        //Object ad = beans.getBean("accountDao", AccountDaoImpl.class);
        System.out.println(as);
       // System.out.println(ad);
        //is.saveAccount();
    }
}

AccountServiceImpl

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;

import com.itheima.service.IAccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
//用注解 并写上acountService 即可利用ApplicationContext取得该对象
@Service("acountService")
public class AccountServiceImpl implements IAccountService {
   // IAccountDao id = new AccountDaoImpl();
    @Resource(name="accountDao")
    private IAccountDao accountDao=null;
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

AccountDaoImpl

package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    public void saveAccount() {
        System.out.println("账户已经保存");
    }
}

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"
       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在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
    context名称空间和约束中-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

3. spring通过注解配置实现

package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Calendar;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml") //就是这个重要
public class AccountServiceTest {

    @Autowired
    private  IAccountService as;

    @Test
    public void testFindAll() {
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne() {
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345f);
        //3.执行方法
        as.saveAccount(account);

    }

    @Test
    public void testUpdate() {
        //3.执行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //3.执行方法
        as.deleteAccount(4);
    }
}

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦