栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第一章 ---- Spring IOC

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第一章 ---- Spring IOC

文章目录

IOC

Spring 简介

Spring是什么Spring优势Spring体系结构Spring发展 IoC简介

引例IoC概念 入门案例IoC配置(XML格式)

bean

基本属性(id,name,class)scopebean生命周期(init-method,destroy-method)工厂bean

factory-beanfactory-bean,factory-method DI

set注入(主流)构造注入(了解)集合注入(array,list,set,map,props) properties文件团队开发ApplicationContext第三方资源配置

Druid数据源 综合案例

基础准备

坐标业务类接口

数据表业务类,接口 基础配置文件测试类 常见问题

IOC Spring 简介 Spring是什么

spring是分层的JavaSE/EE 应用 full-stack 轻量级 开源 框架
框架作用:

提高开发效率增强可重用性提供编写规范节约维护成本解耦底层实现原理 Spring优势

方便解耦,简化开发方便继承各种优秀框架方便程序的测试AOP编程支持声明式事务支持降低JavaEE API的使用难度Java原码是经典的学习范例 Spring体系结构

Spring发展

IoC简介 引例




IoC概念


入门案例

    pom.xml
    

        
            org.springframework
            spring-context
            5.1.9.RELEASE
        
    
    UserService & UserServiceImpl
package com.zs.service;

public interface UserService {
    void save();
}

package com.zs.service.impl;

import com.zs.service.UserService;

public class UserServiceImpl  implements UserService {
    @Override
    public void save() {
        System.out.println("hello spring!!");
    }
}
    建立spring配置文件


    
    

    启动类
package com.zs;

import com.zs.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserApp {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取资源
        UserService userService = (UserService) ctx.getBean("userService");

        userService.save();
    }
}

IoC配置(XML格式) bean 基本属性(id,name,class)

作用: 定义spring中的资源,受此标签定义的资源将受到spring控制


id: bean的名称,通过id值获取beanclass: bean的类型name: bean的名称,可以通过name值获取bean,用于多人配合时给bean起别名

采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建

scope

作用:定义bean的作用范围


默认就是单例的,单例时对象是在spring容器加载时创建,非单例时在对象创建时创建

singleton: 设定创建出的对象保存在spring容器中,是一个单例的对象prototype: 设定创建出的对象保存在spring容器中,是一个非单例的对象request、session、applicaiton、websocket:设定创建出的对象放置在web容器对应的位置 bean生命周期(init-method,destroy-method)

作用:定义bean对象在初始化或销毁时完成的工作


bean对应的类中对应的具体方法名 init(),destroy()
单例模式:只创建一次,init()做一次,ClassPathXmlApplicationContext的close()方法关闭时调用destroy()
非单例:创建一次,调一次,销毁方法不受spring管

工厂bean factory-bean

作用:定义bean对象创建方式,使用静态工厂的形式创建bean,兼容早期遗留系统的升级工作


public class UserServiceFactory {
    public static UserService getService(){
        return new UserServiceImpl();
    }
}
factory-bean,factory-method

作用:定义bean对象创建方式,使用实例工厂的形式创建bean,兼容早期遗留系统的升级工作




public class UserServiceFactory {
    public UserService getService(){
        return new UserServiceImpl();
    }
}
DI

DI依赖注入,应用程序运行依赖的资源由Spring为其提供,资源进入应用程序的方式称为注入
DI其实就是IoC容器,只是站在应用程序的角度的称呼

set注入(主流)
public class UserServiceImpl  implements UserService {
	
	//要注入的属性
    private UserDao userDao;
    private int num;
    private Integer age;
    private String name;

	//提供set方法
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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



    @Override
    public void save() {
        System.out.println("hello spring!!");
        userDao.save();
        System.out.println(num + " " + age + " " + name);
    }
}


    
    
        
        
        
        
        
    
    
    

构造注入(了解)
public class UserServiceImpl  implements UserService {

    private UserDao userDao;
    private int num;
    private Integer age;
    private String name;

    public UserServiceImpl() {
    }

	//提供构造器
    public UserServiceImpl(UserDao userDao, int num, Integer age, String name) {
        this.userDao = userDao;
        this.num = num;
        this.age = age;
        this.name = name;
    }
    
    
        
        
        
        
    
    
    
集合注入(array,list,set,map,props)
public class BookDaoImpl implements BookDao {

    private ArrayList al;
    private Properties properties;
    private int[] arr;
    private HashSet hs;
    private HashMap hm;

    public void setAl(ArrayList al) {
        this.al = al;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setArr(int[] arr) {
        this.arr = arr;
    }

    public void setHs(HashSet hs) {
        this.hs = hs;
    }

    public void setHm(HashMap hm) {
        this.hm = hm;
    }

    @Override
    public void save() {
        System.out.println("book dao running..");
        System.out.println("ArrayList" + al);
        System.out.println("Properties: " + properties);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        System.out.println("HashSet: " + hs);
        System.out.println("HashMap: " + hm);
    }
}

    
    
        
        
    
    
    
    
        
        
            
                12
                zs
            
        
        
            
                zs
                666
            
        
        
            
                12
                13
            
        
        
            
                age
                name
            
        
        
            
                
                
            
        
    

properties文件
public class UserDaoImpl implements UserDao {

    private String username;
    private String password;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void save() {
        System.out.println(username + "t" + password);
    }
}




    
    

    
    
        
        
    
    
    
        
        
    
username=zs666
password=123adfasdf
团队开发


applicationContext.xml




    
    
    
    


applicationContext-book.xml







    
        
        
            
                12
                zs
            
        
        
            
                zs
                666
            
        
        
            
                12
                13
            
        
        
            
                age
                name
            
        
        
            
                
                
            
        
    




applicationContext-user.xml




    
    

    
    
        
        
    
    
    
        
        
    


ApplicationContext


第三方资源配置 Druid数据源

测试

        DruidDataSource druidDataSource = new DruidDataSource();
        System.out.println(druidDataSource);
        
            
            
            
            
        


    4.0.0

    org.example
    spring_1
    1.0-SNAPSHOT

    
        8
        8
    

    

        
            org.springframework
            spring-context
            5.1.9.RELEASE
        
        
            com.alibaba
            druid
            1.1.21
        
    

    
        
            aliyun-maven
            aliyun maven
            http://maven.aliyun.com/nexus/content/groups/public/
        
    
    
        
            aliyun-maven
            aliyun maven
            http://maven.aliyun.com/nexus/content/groups/public/
        
    



综合案例


基础准备 坐标


    4.0.0

    org.example
    spring_1
    1.0-SNAPSHOT

    
        8
        8
    

    
		
		
        
            org.springframework
            spring-context
            5.1.9.RELEASE
        
        
        
            org.springframework
            spring-jdbc
            5.1.9.RELEASE
        
		
        
        
            com.alibaba
            druid
            1.1.21
        
		
        
        
            org.mybatis
            mybatis
            3.5.3
        
        
        
            org.mybatis
            mybatis-spring
            1.3.0
        
		
		
        
            mysql
            mysql-connector-java
            5.1.47
        



    

    
        
            aliyun-maven
            aliyun maven
            http://maven.aliyun.com/nexus/content/groups/public/
        
    
    
        
            aliyun-maven
            aliyun maven
            http://maven.aliyun.com/nexus/content/groups/public/
        
    



业务类接口 数据表
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);
业务类,接口

AccountDao

package com.zs.dao;

import com.zs.domain.Account;

import java.util.List;

public interface AccountDao {
    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List findAll();

    Account findById(Integer id);
}

AccountService

package com.zs.service;

import com.zs.domain.Account;

import java.util.List;

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List findAll();

    Account findById(Integer id);
}

AccountServiceImpl

package com.zs.service.impl;

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

import java.util.List;

public class AccountServiceImpl implements AccountService {

    //使用Spring注入dao
    private AccountDao accountDao;
	//提供set方法
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

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

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

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

    @Override
    public List findAll() {
        return accountDao.findAll();
    }

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

基础配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.username=iplat62
jdbc.password=iplat62

SqlMapConfig.xml.bak :该文件被spring替换成bean




	
    
    
    
        
    
    
    
        
            
            
                
                
                
                
            
        
    
    
    
        
    


AccountDao.xml




    
    
        select * from account
    

    
    
        insert into account(name,money) values(#{name},#{money})
    
    
    
        delete from account where id = #{id}
    

    
    
        update account set name = #{name},money=#{money} where id=#{id}
    




applicationContext.xml




    
    
 	
 	
    
        
        
        
        
    
   
    
    
        
    


    
    
        
        
        
    

    
    
        
    



测试类
package com.zs;

import com.alibaba.druid.pool.DruidDataSource;
import com.zs.domain.Account;
import com.zs.service.AccountService;
import com.zs.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UserApp {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) ctx.getBean("accountService");
        Account byId = accountService.findById(1);
        List all = accountService.findAll();
        System.out.println(byId);
        all.forEach(System.out::println);
    }
}

常见问题

Exception in thread "main" org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.zs.dao.AccountDao.findById
文件位置应该放到对应包下,对应包名需要注意是否只建立了一个包(下图是正确位置的截图)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768974.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号