其他分享
首页 > 其他分享> > SpringIOC

SpringIOC

作者:互联网

Spring 是分层的javaSE/EE的全栈式轻量级开源框架

1.自定义IOC容器

package com.rf.service.Impl;

import com.rf.dao.Impl.UserDaoImpl;
import com.rf.dao.UserDao;
import com.rf.service.UserService;
import com.rf.utils.BeanFactory;

public class UserServiceImpl implements UserService {
    public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //传统方式
        // UserDao userDao = new UserDaoImpl();

        //反射机制获取,解决了编译期依赖的问题
        //UserDao userDao = (UserDao) Class.forName("com.rf.dao.Impl.UserDaoImpl").newInstance();
        
        //出现了硬编码问题,通过配置文件解决
        UserDao userDao = (UserDao) BeanFactory.getInstance("userDao");
        userDao.save();
    }
}
package com.rf.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class BeanFactory {
    private static HashMap<String,Object> iocmap=new HashMap<>();

    //静态代码块加载
    static {
        //1,获取配置文件
        InputStream resource = BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml");
        //2.创建SaxReader 对象
        SAXReader saxReader = new SAXReader();
        //3. 使用dom4j解析文件
        try {
            Document document = saxReader.read(resource);

            //获取节点
            String xpath="//bean";
            List<Element> list = document.selectNodes(xpath);

            for (Element element : list) {
                String id = element.attributeValue("id");
                String classname = element.attributeValue("class");
                Object o = Class.forName(classname).newInstance();
                iocmap.put(id,o);
            }

        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public static Object getInstance(String id){
        return iocmap.get(id);
    }
}
<beans>
    <bean id="userDao" class="com.rf.dao.Impl.UserDaoImpl"></bean>
</beans>

2.spring快速入门

public interface UserDao {
    public void save();
}

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("dao被调用了.....");
    }
}
ApplicationContext.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="userDao" class="com.dao.impl.UserDaoImpl"></bean>

</beans>
    @Test
    public void test01(){
        ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        userDao.save();
    }

3. spring API

    @Test
    public void test02(){
        //通过BeanFactory创建,不会立即创建所有对象实例
        BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("ApplicationContext.xml")) ;
        //当调用getbean方法会创建该对象对应的实例
        UserDao userDao = (UserDao) beanFactory.getBean("userDao");
        userDao.save();
    }
   @Test
    public void test01(){
        //应用上下文 ,从类路径实现
        // ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //磁盘文件实现
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("D:\\学习资料\\java小白学习资料\\java跟课学\\第六阶段\\模块二\\springquickstart\\src\\main\\resources\\ApplicationContext.xml");

        //通过字符串获取对象,需要强制转换
       // UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        //通过泛型获取对象,
        // <bean id="userDao" class="com.dao.impl.UserDaoImpl"></bean>
        //<!--当出现多个类型匹配改类型时,对象无法获取-->
        //    <bean id="userDao2" class="com.dao.impl.UserDaoImpl"></bean>
        UserDao userDao = applicationContext.getBean(UserDao.class);
        userDao.save();
    }

4. Bean

取值范围

说明
singleton 默认值,单例的
prototype 多例的
request WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中
session WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中
global
session
WEB项目中,应用在Portlet环境,如果没有Portlet环境那么globalSession 相当
于 session
  //singleton 只创建一个实例
        UserDao userDao = (UserDao) beanFactory.getBean("userDao");//com.dao.impl.UserDaoImpl@f79e
        UserDao userDao1 = (UserDao) beanFactory.getBean("userDao");//   com.dao.impl.UserDaoImpl@f79e
        System.out.println(userDao);
        System.out.println(userDao1);
        //prototype
        UserDao userDao2 = (UserDao) beanFactory.getBean("userDao2");//com.dao.impl.UserDaoImpl@7ee8290b
        UserDao userDao3 = (UserDao) beanFactory.getBean("userDao2");// com.dao.impl.UserDaoImpl@1f59a598
        System.out.println(userDao2);
        System.out.println(userDao3);
<!--方式一 无参方法构造-->
    <bean id="userDao" class="com.dao.impl.UserDaoImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean>
<!--当出现多个类型匹配改类型时,对象无法获取-->
    <bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype"></bean>
<!-- 方式二 静态工厂模式-->
    <bean id="staticUser" class="com.factory.StaticBeanFactory" factory-method="createUserDao"></bean>
<!-- 方式三 普通工厂模式-->
    <bean id="CommonBeanFactory" class="com.factory.CommonBeanFactory"></bean>
    <bean id="commonUser" factory-bean="CommonBeanFactory" factory-method="createUserDao"></bean>

5. bean依赖注入

依赖注入 DI(Dependency Injection):它是 Spring 框架核心 IOC 的具体实实现,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。IOC 解耦只是降低他们的依赖关系,但不会消除。需要通过spring框架把持久层对象传入到业务层

<!--构造方法注入-->
    <bean id="userService" class="com.service.impl.UserServiceImpl">
<!--        <constructor-arg index="0" type="com.dao.UserDao" ref="userDao"/>-->
        <constructor-arg name="userDao" ref="userDao"></constructor-arg>
    </bean>

 private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

 

<!-- set 方法-->
    <bean id="userService" class="com.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

 public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
<bean id="userService" class="com.service.impl.UserServiceImpl" p:userDao-ref="userDao">
    </bean>

7.基于spring.xml整合的DbUtils

CREATE DATABASE `spring_db`;
USE `spring_db`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000),
(2,'jerry',1000);
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
package com.domain;

public class Account {
    private int id;
    private String name;
    private double money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}
package com.dao.impl;

import com.dao.AccountDao;
import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImp implements AccountDao {
    private QueryRunner qr;

    public QueryRunner getQr() {
        return qr;
    }

    public void setQr(QueryRunner qr) {
        this.qr = qr;
    }

    public List<Account> findAll() {
        List<Account> query=null;
        String sql="select * from account";
        try {
           query= qr.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public Account findById(Integer id) {
      Account account=null;
        
        try {
            String sql="select * from account where id=?";
            account = qr.query(sql, new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return account;
    }

    public void save(Account account) {
        
        try {
            String sql="insert into account values (null,?,?)";
            qr.update(sql, account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
      
    }

    public void update(Account account) {
        try {
            String sql="update account set name=?, money = ? where id=?";
            qr.update(sql, account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void delete(Integer id) {
        try {
            String sql="delete from account where id=?";
            qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
package com.service.impl;

import com.dao.AccountDao;
import com.domain.Account;
import com.service.AccountService;

import java.util.List;

public class AccountServiceImp implements AccountService {
    private AccountDao accountDao;

    public AccountDao getAccountDao() {
        return accountDao;
    }

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

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

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

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

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

    public void delete(Integer id) {
        accountDao.delete(id);
    }
}
<?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
">


    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- datasource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- queryrunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!-- accountdao-->
    <bean id="accountDao" class="com.dao.impl.AccountDaoImp">
        <property name="qr" ref="queryRunner"></property>
    </bean>
    <!-- acocuntservice-->
    <bean id="accountService" class="com.service.impl.AccountServiceImp">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
</beans>
package com.test;

import com.domain.Account;
import com.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class test {
   ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountService accountService = (AccountService) applicationContext.getBean("accountService");

@Test
    public void test01(){
        List<Account> accountList = accountService.findAll();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }
    @Test
    public void test02(){
        Account account = new Account();
        account.setName("lucy");
        account.setMoney(888d);
        accountService.save(account);
    }
    @Test
    public void test03(){
        Account account = accountService.findById(3);
        System.out.println(account);
    }

    @Test
    public void test04(){
        Account account = new Account();
        account.setId(3);
        account.setName("jack");
        account.setMoney(9999d);
        accountService.update(account);
    }

    @Test
    public void test05(){
         accountService.delete(3);

    }
}

8. spring注解

 JDK11以后完全移除了javax扩展导致不能使用@resource注解

<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>

使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法

<!--注解的组件扫描-->
<context:component-scan base-package="com.lagou"></context:component-scan>
非自定义的Bean的配置:<bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置:<context:component-scan>
引入其他文件:<import> 
注解 说明
@Configuration 用于指定当前类是一个Spring 配置类,当创建容器时会从该类上加载注解
@Bean 使用在方法上,标注将该方法的返回值存储到 Spring 容器中
@PropertySource 用于加载 properties 文件中的配置
@ComponentScan 用于指定 Spring 在初始化容器时要扫描的包
@Import 用于导入其他配置类

 

9.完全注解进行DbUtils开发

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springdb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
<!--resource 注解不可用,因为JDK11以后完全移除了javax扩展-->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

    </dependencies>
</project>
package com.domain;

public class Account {
    private int id;
    private String name;
    private double money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}



package com.dao.impl;

import com.dao.AccountDao;
import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository("accountDao")
public class AccountDaoImp implements AccountDao {

    @Autowired
    private QueryRunner queryRunner;


    public List<Account> findAll() {
        List<Account> query=null;
        String sql="select * from account";
        try {
           query= queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public Account findById(Integer id) {
      Account account=null;

        try {
            String sql="select * from account where id=?";
            account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return account;
    }

    public void save(Account account) {

        try {
            String sql="insert into account values (null,?,?)";
            queryRunner.update(sql, account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void update(Account account) {
        try {
            String sql="update account set name=?, money = ? where id=?";
            queryRunner.update(sql, account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void delete(Integer id) {
        try {
            String sql="delete from account where id=?";
            queryRunner.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

package com.dao;

import com.domain.Account;

import java.util.List;

public interface AccountDao {
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}

package com.service.impl;

import com.dao.AccountDao;
import com.domain.Account;
import com.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("accountService")
public class AccountServiceImp implements AccountService {

    @Autowired
//    @Qualifier("accountDao")
//    @Resource(name = "accountDao")
    private AccountDao accountDao;

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

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

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

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

    public void delete(Integer id) {
        accountDao.delete(id);
    }
}

package com.service;

import com.domain.Account;

import java.util.List;

public interface AccountService {
    public List<Account> findAll();
    public Account findById(Integer id);
    public void save(Account account);
    public void update(Account account);
    public void delete(Integer id);
}
package com.test;

import com.config.SpringConfig;
import com.domain.Account;
import com.service.AccountService;
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.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class test {
//使用注解方式
//ApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class);
//    AccountService accountService = (AccountService) applicationContext.getBean("accountService");
    @Autowired
    private AccountService accountService;
@Test
    public void test01(){

    List<Account> accountList = accountService.findAll();
        for (Account account : accountList) {
            System.out.println(account);
        }
    }
    @Test
    public void test02(){
        Account account = new Account();
        account.setName("lucy");
        account.setMoney(888d);
        accountService.save(account);
    }
    @Test
    public void test03(){
        Account account = accountService.findById(3);
        System.out.println(account);
    }

    @Test
    public void test04(){
        Account account = new Account();
        account.setId(3);
        account.setName("jack");
        account.setMoney(9999d);
        accountService.update(account);
    }

    @Test
    public void test05(){
         accountService.delete(3);

    }
}

 

      



     

 

 

标签:account,SpringIOC,Account,id,import,com,public
来源: https://www.cnblogs.com/forever-fate/p/15016561.html