菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
465
0

IoC COntainer Create Javabeans 可以通过读取beans.xml 文件来创建一个应用程序上下文对象 依赖反转

原创
05/13 14:22
阅读数 5297

 

 

Spring初学快速入门 - Spring教程™ https://www.yiibai.com/spring/spring-tutorial-for-beginners.html#

pom

<?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>com.yiibai</groupId>
<artifactId>HelloSpring</artifactId>
<version>0.0.1-SNAPSHOT</version>


<dependencies>

<!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>

<!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>

</dependencies>
</project>

D:\worksp\spring\src\main\resources\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 id="springHelloWorld" class="com.yiibai.tutorial.spring.helloworld.impl.SpringHelloWorld"></bean>
<bean id="strutsHelloWorld" class="com.yiibai.tutorial.spring.helloworld.impl.StrutsHelloWorld"></bean>
<bean id="helloWorldService" class="com.yiibai.tutorial.spring.helloworld.HelloWorldService">
<!--<property name="helloWorld" ref="springHelloWorld"/>-->
<property name="helloWorld" ref="strutsHelloWorld"/>
</bean>
</beans>



└── spring
    ├── pom.xml
    ├── spring.iml
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── yiibai
    │   │   │           └── tutorial
    │   │   │               └── spring
    │   │   │                   ├── HelloProgram.java
    │   │   │                   └── helloworld
    │   │   │                       ├── HelloWorld.java
    │   │   │                       ├── HelloWorldService.java
    │   │   │                       └── impl
    │   │   │                           ├── SpringHelloWorld.java
    │   │   │                           └── StrutsHelloWorld.java
    │   │   └── resources
    │   │       └── beans.xml
    │   └── test
    │       └── java
    └── target
        ├── classes
        │   ├── beans.xml
        │   └── com
        │       └── yiibai
        │           └── tutorial
        │               └── spring
        │                   ├── HelloProgram.class
        │                   └── helloworld
        │                       ├── HelloWorld.class
        │                       ├── HelloWorldService.class
        │                       └── impl
        │                           ├── SpringHelloWorld.class
        │                           └── StrutsHelloWorld.class
        └── generated-sources
            └── annotations

  

D:\worksp\spring\src\main\java\com\yiibai\tutorial\spring\helloworld\impl\SpringHelloWorld.java
package com.yiibai.tutorial.spring.helloworld.impl;

import com.yiibai.tutorial.spring.helloworld.HelloWorld;

public class SpringHelloWorld implements HelloWorld {
@Override
public void sayHello(){
System.out.println("Spring Say Hello");
}
}

D:\worksp\spring\src\main\java\com\yiibai\tutorial\spring\helloworld\impl\StrutsHelloWorld.java

package com.yiibai.tutorial.spring.helloworld.impl;

import com.yiibai.tutorial.spring.helloworld.HelloWorld;

public class StrutsHelloWorld implements HelloWorld {
@Override
public void sayHello() {
System.out.println("Struts Say Hello!");
}
}

D:\worksp\spring\src\main\java\com\yiibai\tutorial\spring\helloworld\HelloWorld.java
package com.yiibai.tutorial.spring.helloworld;

public interface HelloWorld {
public void sayHello();
}

D:\worksp\spring\src\main\java\com\yiibai\tutorial\spring\helloworld\HelloWorldService.java
package com.yiibai.tutorial.spring.helloworld;

public class HelloWorldService {
private HelloWorld helloWorld;

public HelloWorldService() {

}

public void setHelloWorld(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}

public HelloWorld getHelloWorld() {
return this.helloWorld;
}
}

D:\worksp\spring\src\main\java\com\yiibai\tutorial\spring\HelloProgram.java

package com.yiibai.tutorial.spring;

import com.yiibai.tutorial.spring.helloworld.HelloWorld;
import com.yiibai.tutorial.spring.helloworld.HelloWorldService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloProgram {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");
HelloWorld hw = service.getHelloWorld();
hw.sayHello();
}
}


【"控制反转"是指new实例工作不由程序员来做而是交给Spring容器来做】
https://www.w3cschool.cn/wkspring/f8pc1hae.html

由 陈 创建,Carrie 最后一次修改 2016-08-12

IoC 容器

Spring 容器是 Spring 框架的核心。容器将创建对象,把它们连接在一起,配置它们,并管理他们的整个生命周期从创建到销毁。Spring 容器使用依赖注入(DI)来管理组成一个应用程序的组件。这些对象被称为 Spring Beans,我们将在下一章中进行讨论。

通过阅读配置元数据提供的指令,容器知道对哪些对象进行实例化,配置和组装。配置元数据可以通过 XML,Java 注释或 Java 代码来表示。下图是 Spring 如何工作的高级视图。 Spring IoC 容器利用 Java 的 POJO 类和配置元数据来生成完全配置和可执行的系统或应用程序。

IOC 容器具有依赖注入功能的容器,它可以创建对象,IOC 容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。通常new一个实例,控制权由程序员控制,而"控制反转"是指new实例工作不由程序员来做而是交给Spring容器来做。在Spring中BeanFactory是IOC容器的实际代表者。

Spring 提供了以下两种不同类型的容器。

序号容器 & 描述
1 Spring BeanFactory 容器

它是最简单的容器,给 DI 提供了基本的支持,它用 org.springframework.beans.factory.BeanFactory 接口来定义。BeanFactory 或者相关的接口,如 BeanFactoryAware,InitializingBean,DisposableBean,在 Spring 中仍然存在具有大量的与 Spring 整合的第三方框架的反向兼容性的目的。

2 Spring ApplicationContext 容器

该容器添加了更多的企业特定的功能,例如从一个属性文件中解析文本信息的能力,发布应用程序事件给感兴趣的事件监听器的能力。该容器是由 org.springframework.context.ApplicationContext 接口定义。

ApplicationContext 容器包括 BeanFactory 容器的所有功能,所以通常建议超过 BeanFactory。BeanFactory 仍然可以用于轻量级的应用程序,如移动设备或基于 applet 的应用程序,其中它的数据量和速度是显著。

 

 

Spring BeanFactory 容器

由 陈 创建,Carrie 最后一次修改 2016-08-12

Sping 的 BeanFactory 容器

这是一个最简单的容器,它主要的功能是为依赖注入 (DI) 提供支持,这个容器接口在 org.springframework.beans.factory.BeanFactor 中被定义。BeanFactory 和相关的接口,比如BeanFactoryAware、DisposableBean、InitializingBean,仍旧保留在 Spring 中,主要目的是向后兼容已经存在的和那些 Spring 整合在一起的第三方框架。

在 Spring 中,有大量对 BeanFactory 接口的实现。其中,最常被使用的是 XmlBeanFactory 类。这个容器从一个 XML 文件中读取配置元数据,由这些元数据来生成一个被配置化的系统或者应用。

在资源宝贵的移动设备或者基于 applet 的应用当中, BeanFactory 会被优先选择。否则,一般使用的是 ApplicationContext,除非你有更好的理由选择 BeanFactory。

例子:

假设我们已经安装 Eclipse IDE,按照下面的步骤,我们可以创建一个 Spring 应用程序。

步骤描述
1 创建一个名为 SpringExample 的工程并在 src 文件夹下新建一个名为 com.tutorialspoint 文件夹。
2 点击右键,选择 Add External JARs 选项,导入 Spring 的库文件,正如我们在 Spring Hello World Example 章节中提到的导入方式。
3 在 com.tutorialspoint 文件夹下创建 HelloWorld.java 和 MainApp.java两个类文件。
4 在 src 文件夹下创建 Bean 的配置文件 Beans.xml
5 最后的步骤是创建所有 Java 文件和 Bean 的配置文件的内容,按照如下所示步骤运行应用程序。

下面是文件 HelloWorld.java 的内容:

package com.tutorialspoint;
public class HelloWorld {
   private String message;
   public void setMessage(String message){
    this.message  = message;
   }
   public void getMessage(){
    System.out.println("Your Message : " + message);
   }
}

下面是文件 MainApp.java 的内容:

package com.tutorialspoint;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
   public static void main(String[] args) {
      XmlBeanFactory factory = new XmlBeanFactory
                             (new ClassPathResource("Beans.xml"));
      HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
      obj.getMessage();
   }
}

在主程序当中,我们需要注意以下两点:

  • 第一步利用框架提供的 XmlBeanFactory() API 去生成工厂 bean 以及利用 ClassPathResource() API 去加载在路径 CLASSPATH 下可用的 bean 配置文件。XmlBeanFactory() API 负责创建并初始化所有的对象,即在配置文件中提到的 bean。

  • 第二步利用第一步生成的 bean 工厂对象的 getBean() 方法得到所需要的 bean。 这个方法通过配置文件中的 bean ID 来返回一个真正的对象,该对象最后可以用于实际的对象。一旦得到这个对象,你就可以利用这个对象来调用任何方法。

下面是配置文件 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-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

如果你已经完成上面的内容,接下来,让我们运行这个应用程序。如果程序没有错误,你将从控制台看到以下信息:

Your Message : Hello


.
└── spring
    ├── pom.xml
    ├── spring.iml
    ├── src
    │   └── main
    │       ├── java
    │       │   └── com
    │       │       └── tutorialspoint
    │       │           ├── HelloWorld.java
    │       │           └── MainApp.java
    │       └── resources
    │           └── beans.xml
    └── target

  D:\worksp\spring\src\main\resources\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 id="helloWorld" class="com.tutorialspoint.HelloWorld">
<property name="message" value="writeInBean"/>
</bean>
</beans>

D:\worksp\spring\src\main\java\com\tutorialspoint\HelloWorld.java
package com.tutorialspoint;

public class HelloWorld {
private String message;

public void setMessage(String message) {
this.message = message;
}

public void getMessage() {
System.out.println("Your message:" + message);
}
}

D:\worksp\spring\src\main\java\com\tutorialspoint\MainApp.java
package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWord");
obj.getMessage();
}
}

十一月 28, 2018 5:32:08 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@20ad9418: startup date [Wed Nov 28 17:32:08 CST 2018]; root of context hierarchy
十一月 28, 2018 5:32:08 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'helloWord' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:694)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at com.tutorialspoint.MainApp.main(MainApp.java:10)

 

 

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}


十一月 28, 2018 5:32:25 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@20ad9418: startup date [Wed Nov 28 17:32:25 CST 2018]; root of context hierarchy
十一月 28, 2018 5:32:26 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
Your message:writeInBean

 

发表评论

0/200
465 点赞
0 评论
收藏