Spring的IOC

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="值"

 

代码如下

public interface UserService {
    public void save();
}
复制代码
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");
    }
}
复制代码
复制代码
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

复制代码
<?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

复制代码
<?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>
复制代码

执行

复制代码
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();
    }
}
复制代码

得到结果

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)

 

代码如下

public interface UserDAO {
    public void save();
}
public interface UserService {
    public void save();
}
复制代码
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");
    }

}
复制代码
复制代码
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被执行了");
    }
}
复制代码

配置文件

<?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>

执行

复制代码
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();
    }
}
复制代码

输出结果

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,注解完成属性注入

欢迎关注我的微信公众号:安卓圈

posted @   嘉禾世兴  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2016-06-11 C向C++改造
点击右上角即可分享
微信分享提示