前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringIOC

SpringIOC

作者头像
用户3112896
发布2019-09-26 14:57:01
3770
发布2019-09-26 14:57:01
举报
文章被收录于专栏:安卓圈安卓圈

XML方式:

IOC:控制反转的底层原理就是:工厂模式+反射+配置文件 DI:依赖注入就是通过配置文件设置属性值

BeanFactory 是老版本的工厂类:调用getBean的时候,才会生成类的实例 ApplicationContext 是新版本的工厂类:加载配置文件的时候,就会将Spring管理的类都实例化

ApplicationContext有两个实现类: ClassPathXmlApplicationContext :加载类路径下的配置文件 FileSystemXmlApplicationContext :加载文件系统下的配置文件

<bean>标签 id 使用了约束中的唯一约束,里面不能出现特殊字符 name 没有使用约束中的唯一约束(理论上可以重复,实际开发中不能出现重复),可以出现特殊字符

bean生命周期的配置 init-method:Bean被初始化的时候执行的方法 destroy-method: Bean被销毁的时候的方法(Bean是单例创建,工厂关闭)

Bean作用范围的配置: scope Bean的作用范围 singleton 默认的,Spring会采用单例模式创建这个对象 prototype 多例模式,用一次new一个(Struts2和spring整合的时候一定会用到)

P名称空间的属性注入 普通属性   p:属性名="值" 对象属性   p:属性名-ref="值"

代码如下

代码语言:javascript
复制
public interface UserService {
    public void save();
}
代码语言:javascript
复制
public class UserServiceImpl implements UserService {
    private String name;
    private String age;
    private String price;
    private Student student;

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

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

    public void setPrice(String price) {
        this.price = price;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public void save() {
        System.out.println("save..name=" + name + ";age=" + age + ";price=" + price + ";student=" + student);
    }

    public void init() {
        System.out.println("init");
    }

    public void destroy() {
        System.out.println("destroy");
    }
}
代码语言:javascript
复制
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Student {
    private String name;
    private String[] arrs;
    private List<String> list;
    private Set<String> set;
    private Map<String, String> map;

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

    public void setArrs(String[] arrs) {
        this.arrs = arrs;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }


    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", arrs=" + Arrays.toString(arrs) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                '}';
    }
}

配置文件

ApplicationContext.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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.jinke.demo.UserServiceImpl" init-method="init" destroy-method="destroy"
          p:age="30" p:price="2000" p:student-ref="student">
        <property name="name" value="李东"/>
    </bean>
    <import resource="ApplicationContext2.xml"/>
</beans>

ApplicationContext2.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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="student" class="com.jinke.demo.Student" p:name="学生">
        <property name="arrs">
            <list>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
            </list>
        </property>
        <property name="list">
            <list>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </list>
        </property>
        <property name="set">
            <set>
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </set>
        </property>
        <property name="map">
            <map>
                <entry key="1" value="a"/>
                <entry key="2" value="b"/>
                <entry key="3" value="c"/>
            </map>
        </property>
    </bean>

</beans>

执行

代码语言:javascript
复制
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemo1 {

    @Test
    public void demo() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userDAO");
        userService.save();
        ((ClassPathXmlApplicationContext) applicationContext).close();
    }
}

得到结果

代码语言:javascript
复制
save..name=李东;age=30;price=2000;student=Student{name='学生', arrs=[张三, 李四, 王五], list=[1, 2, 3], set=[a, b, c], map={1=a, 2=b, 3=c}}
六月 11, 2019 6:40:17 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@6842775d: startup date [Tue Jun 11 18:40:16 CST 2019]; root of context hierarchy
destroy

注解的方式

Spring包括的模块

web层:springmvc service层:bean管理,声明式事物 DAO层:ORM模块、jdbc模板

IOC注解方式,可以不提供set方法 属性如果有set方法,注解添加到set方法上,没有set方法就添加到属性上

注解详解 @Component:组件 衍生:@Controller web层的类、@Service service层的类、@Repository DAO层的类(一般用这个)

普通属性:@Value 对象属性:@Autowired 习惯是和@Qualifier一起使用

@Resource(一般用这个)

生命周期相关注解 @PostConsruct 初始化 @PreDestroy 销毁

Bean作用范围 @Scope(singleton/prototype)

代码如下

代码语言:javascript
复制
public interface UserDAO {
    public void save();
}
代码语言:javascript
复制
public interface UserService {
    public void save();
}
代码语言:javascript
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Repository(value = "userDao")//相当于<bean id = "userDao" class="com.jinke.demo1.UserDAOImpl"/>
public class UserDAOImpl implements UserDAO {
    @Value("大傻")
    private String name;

    /*@Value("大傻")
    public void setName(String name) {
        this.name = name;
    }*/
    /*@Autowired
    @Qualifier(value = "userService222")*/
    @Resource(name = "userService222")
    private UserService userService;

    @Override
    public void save() {
        System.out.println("UserDAOImpl被执行了--name=" + name);
        userService.save();
    }

    @PostConstruct//相当于init-method
    public void init() {
        System.out.println("UserDAOImpl被执行了init");
    }

    @PreDestroy//相当于destroy-method
    public void destroy() {
        System.out.println("UserDAOImpl被执行了destroy");
    }

}
代码语言:javascript
复制
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("userService222")
@Scope("singleton")
public class UserServiceImpl implements UserService {
    @Override
    public void save() {
        System.out.println("UserServiceImpl的save被执行了");
    }
}

配置文件

代码语言:javascript
复制
<?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:component-scan base-package="com.jinke.demo1"/>
</beans>

执行

代码语言:javascript
复制
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo1 {
    @Test
    public void demo1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext3.xml");
        UserDAO userDao = (UserDAO) applicationContext.getBean("userDao");
        userDao.save();
        ((ClassPathXmlApplicationContext) applicationContext).close();
    }
}

输出结果

代码语言:javascript
复制
UserDAOImpl被执行了init
UserDAOImpl被执行了--name=大傻
UserServiceImpl的save被执行了
六月 12, 2019 4:25:36 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@6842775d: startup date [Wed Jun 12 16:25:36 CST 2019]; root of context hierarchy
UserDAOImpl被执行了destroy

总结:一般XML用来管理Bean,注解完成属性注入

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档