关于java:Java开发之Spring框架入门学习

管制反转-IOC

步骤:

导入相干jar包 lib

编写Spring配置文java培训件(名称可自定义), beans.xml

定义类:

package com.xj.bean;

public class Hello {

private String name;


public Hello() {
    System.out.println("Hello对象被创立");
}


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


public void show() {
    System.out.println("我敬爱的," + name);
}

}

编写Spring配置文件(名称可自定义), beans.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就是java对象,由spring容器来创立和治理-->
<bean name="hello" class="com.xj.bean.Hello">
<property name="name" value="中国"/>
</bean>

</beans>

测试代码:

package com.xj.test;

import com.xj.bean.Hello;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {
    //解析beans.xml文件,生产相应的bean对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Hello hello = (Hello)context.getBean("hello");
    hello.show();
}

}

output:

十一月 07, 2019 10:02:34 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@244038d0: startup date [Thu Nov 07 22:02:34 CST 2019]; root of context hierarchy
十一月 07, 2019 10:02:34 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
Hello对象被创立
我敬爱的,中国

Process finished with exit code 0

思考:

1、Hello对象是谁创立的?

能够应用hello.show();调用它的办法,阐明Hello对象被创立。

Hello对象是由Spring容器创立的

2、hello对象的属性是怎么设置的(即name怎么失去“中国”的)?

Hello对象的属性是由Spring容器设置的,这个过程就叫管制反转

管制的内容:指谁来管制对象的创立,传统的应用程序对象的创立是由程序自身,应用Spring之后,由Spring来创建对象。

反转:(创建对象的)权限的转移

正转:指程序来创建对象;

反转:指程序自身不去创建对象,而变为被动的去接管由Spring容器创立的对象。

总结:以前对象由程序自身(service实现类)来创立,应用Spring后,程序变为被动接管Spring创立好的对象。

管制反转:–依赖注入(dependency injection)

依赖注入(dependency injection)

比方:Hello类,依赖name,name的值是通过容器来设置的。

反过来,“中国”这个value是通过

public void setName(String name){

this.name = name;

}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理