Spring IoC,Spring Bean示例教程

Welcome to the Spring IoC Example Tutorial. Spring Framework is built on the Inversion of Control principle. Dependency injection is the technique to implement IoC in applications.

欢迎使用Spring IoC示例教程。 Spring框架基于控制反转原则构建。 依赖注入是在应用程序中实现IoC的技术。

SpringIoC (Spring IoC)

spring ioc, spring ioc example, spring ioc tutorial, spring bean

Today we will look into Spring IoC Container. We will also go through Spring Bean. Below is the table to contents for quick navigation to different sections of Spring IoC tutorial.


今天,我们将研究Spring IoC容器。 我们还将介绍Spring Bean。 下表是内容列表,可快速导航到Spring IoC教程的不同部分。

  1. Spring IoC

    SpringIoC
  2. Spring Bean

    Spring Bean
  3. Spring Bean Scopes

    Spring Bean范围
  4. Spring Bean Configuration

    Spring Bean配置
  5. Spring IoC and Spring Bean Example
    1. XML Based Spring Bean Configuration
    2. Annotation Based Spring Bean Configuration
    3. Java Based Spring Bean Configuration

    Spring IoC和Spring Bean示例
    1. 基于XML的Spring Bean配置
    2. 基于注释的Spring Bean配置
    3. 基于Java的Spring Bean配置

SpringIoC容器 (Spring IoC Container)

Spring IoC is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, objects dependencies are injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use. We have already looked how we can use Spring Dependency Injection to implement IoC in our applications.

Spring IoC是一种实现对象依赖关系之间松散耦合的机制。 为了在运行时实现对象的松散耦合和动态绑定,对象依赖项由其他汇编器对象注入。 Spring IoC容器是依赖项注入到对象中并使其可供我们使用的程序。 我们已经研究了如何使用Spring Dependency Injection在我们的应用程序中实现IoC。

Spring IoC container classes are part of org.springframework.beans and org.springframework.context packages. Spring IoC container provides us different ways to decouple the object dependencies.

Spring IoC容器类是org.springframework.beansorg.springframework.context包的一部分。 Spring IoC容器为我们提供了分离对象依赖关系的不同方法。

BeanFactory is the root interface of Spring IoC container. ApplicationContext is the child interface of BeanFactory interface that provide Spring AOP features, i18n etc.

BeanFactory是Spring IoC容器的根接口。 ApplicationContextBeanFactory接口的子接口,提供Spring AOP功能,i18n等。

Some of the useful child-interfaces of ApplicationContext are ConfigurableApplicationContext and WebApplicationContext. Spring Framework provides a number of useful ApplicationContext implementation classes that we can use to get the spring context and then the Spring Bean.

ApplicationContext一些有用的子接口是ConfigurableApplicationContextWebApplicationContext 。 Spring框架提供了许多有用的ApplicationContext实现类,我们可以使用它们来获取Spring上下文,然后获取Spring Bean。

Some of the useful ApplicationContext implementations that we use are;

我们使用的一些有用的ApplicationContext实现是:

  • AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.

    AnnotationConfigApplicationContext :如果我们在独立的Java应用程序中使用Spring并为Configuration使用注释,则可以使用它来初始化容器并获取Bean对象。
  • ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.

    ClassPathXmlApplicationContext :如果在独立应用程序中有spring bean配置xml文件,则可以使用此类加载文件并获取容器对象。
  • FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.

    FileSystemXmlApplicationContext :这类似于ClassPathXmlApplicationContext,不同之处在于可以从文件系统中的任何位置加载xml配置文件。
  • AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

    Web应用程序的AnnotationConfigWebApplicationContextXmlWebApplicationContext

Usually, if you are working on Spring MVC application and your application is configured to use Spring Framework, Spring IoC container gets initialized when the application starts and when a bean is requested, the dependencies are injected automatically.

通常,如果您正在使用Spring MVC应用程序,并且您的应用程序配置为使用Spring Framework,则在启动应用程序和请求Bean时会初始化Spring IoC容器,并自动注入依赖项。

However, for a standalone application, you need to initialize the container somewhere in the application and then use it to get the spring beans.

但是,对于独立应用程序,您需要在应用程序中的某个位置初始化容器,然后使用它来获取spring bean。

Spring Bean (Spring Bean)

Spring Bean is nothing special, any object in the Spring framework that we initialize through Spring container is called Spring Bean. Any normal Java POJO class can be a Spring Bean if it’s configured to be initialized via container by providing configuration metadata information.

Spring Bean没什么特别的,我们通过Spring容器初始化的Spring框架中的任何对象都称为Spring Bean。 如果通过提供配置元数据信息将其配置为通过容器初始化,则任何普通的Java POJO类都可以是Spring Bean。

Spring Bean范围 (Spring Bean Scopes)

There are five scopes defined for Spring Beans.

Spring Bean定义了五个作用域。

  1. singleton – Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues.

    单例 –将为每个容器创建一个bean实例。 这是spring bean的默认范围。 使用此范围时,请确保bean没有共享的实例变量,否则可能导致数据不一致问题。
  2. prototype – A new instance will be created every time the bean is requested.

    prototype –每次请求bean时都会创建一个新实例。
  3. request – This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.

    请求 –与原型范围相同,但是它打算用于Web应用程序。 将为每个HTTP请求创建一个新的bean实例。
  4. session – A new bean will be created for each HTTP session by the container.

    session –容器将为每个HTTP会话创建一个新bean。
  5. global-session – This is used to create global session beans for Portlet applications.

    global-session –用于为Portlet应用程序创建全局会话Bean。

Spring Framework is extendable and we can create our own scopes too. However, most of the times we are good with the scopes provided by the framework.

Spring Framework是可扩展的,我们也可以创建自己的范围。 但是,大多数时候我们对框架提供的范围感到满意。

Spring Bean配置 (Spring Bean Configuration)

Spring Framework provides three ways to configure beans to be used in the application.

Spring Framework提供了三种方法来配置要在应用程序中使用的bean。

  1. Annotation Based Configuration – By using @Service or @Component annotations. Scope details can be provided with @Scope annotation.

    基于注释的配置 –通过使用@Service或@Component注释。 范围详细信息可以通过@Scope注释提供。
  2. XML Based Configuration – By creating Spring Configuration XML file to configure the beans. If you are using Spring MVC framework, the xml based configuration can be loaded automatically by writing some boiler plate code in web.xml file.

    基于XML的配置 –通过创建Spring Configuration XML文件来配置Bean。 如果您使用的是Spring MVC框架,则可以通过在web.xml文件中编写一些样板代码来自动加载基于xml的配置。
  3. Java Based Configuration – Starting from Spring 3.0, we can configure Spring beans using java programs. Some important annotations used for java based configuration are @Configuration, @ComponentScan and @Bean.

    基于Java的配置 –从Spring 3.0开始,我们可以使用Java程序配置Spring Bean。 用于基于Java的配置的一些重要注释是@ Configuration,@ ComponentScan和@Bean。

Spring IoC和Spring Bean示例项目 (Spring IoC and Spring Bean Example Project)

Let’s look at the different aspects of Spring IoC container and Spring Bean configurations with a simple Spring project.

让我们通过一个简单的Spring项目来查看Spring IoC容器和Spring Bean配置的不同方面。

For my example, I am creating a Spring MVC project in Spring Tool Suite. If you are new to Spring Tool Suite and Spring MVC, please read Spring MVC Tutorial with Spring Tool Suite.

对于我的示例,我正在Spring Tool Suite中创建一个Spring MVC项目。 如果您不熟悉Spring Tool Suite和Spring MVC,请阅读Spring Tool Suite的Spring MVC教程

The final project structure looks like below image.

最终的项目结构如下图所示。

Let’s look at different components of Spring IoC and Spring Bean project one by one.

让我们一一看一下Spring IoC和Spring Bean项目的不同组件。

基于XML的Spring Bean配置 (XML Based Spring Bean Configuration)

MyBean is a simple Java POJO class.

MyBean是一个简单的Java POJO类。

package com.journaldev.spring.beans;

public class MyBean {

	private String name;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
Spring配置XML文件 (Spring Configuration XML File)

servlet-context.xml code:

servlet-context.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.journaldev.spring" />
	
	<beans:bean name="myBean" class="com.journaldev.spring.beans.MyBean" scope="singleton" ></beans:bean>
	
</beans:beans>

Notice that MyBean is configured using bean element with scope as singleton.

注意,使用范围为单例的bean元素配置了MyBean。

基于注释的Spring Bean配置 (Annotation Based Spring Bean Configuration)

package com.journaldev.spring.beans;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

@Service
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class MyAnnotatedBean {

	private int empId;

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}
	
}

MyAnnotatedBean is configured using @Service and scope is set to Request.

使用@Service配置MyAnnotatedBean,并将范围设置为Request。

Spring IoC控制器类 (Spring IoC Controller Class)

HomeController class will handle the HTTP requests for the home page of the application. We will inject our Spring beans to this controller class through WebApplicationContext container.

HomeController类将处理对应用程序主页的HTTP请求。 我们将通过WebApplicationContext容器将Spring bean注入此控制器类。

package com.journaldev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.journaldev.spring.beans.MyAnnotatedBean;
import com.journaldev.spring.beans.MyBean;

@Controller
@Scope("request")
public class HomeController {
		
	private MyBean myBean;
	
	private MyAnnotatedBean myAnnotatedBean;

	@Autowired
	public void setMyBean(MyBean myBean) {
		this.myBean = myBean;
	}

	@Autowired
	public void setMyAnnotatedBean(MyAnnotatedBean obj) {
		this.myAnnotatedBean = obj;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		System.out.println("MyBean hashcode="+myBean.hashCode());
		System.out.println("MyAnnotatedBean hashcode="+myAnnotatedBean.hashCode());
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
}

部署描述符 (Deployment Descriptor)

We need to configure our application for Spring Framework so that the configuration metadata will get loaded and context will be initialized.

我们需要为Spring Framework配置应用程序,以便配置元数据将被加载并且上下文将被初始化。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Almost all the configuration above is boiler-plate code generated by STS tool automatically.

上面的几乎所有配置都是STS工具自动生成的样板代码。

运行Spring IoC Bean示例应用程序 (Run the Spring IoC Bean Example Application)

Now when you will launch the web application, the home page will get loaded and in the console following logs will be printed when you refresh the page multiple times.

现在,当您启动Web应用程序时,将加载主页,并在控制台中多次刷新页面时将在日志中打印以下日志。

MyBean hashcode=118267258
MyAnnotatedBean hashcode=1703899856
MyBean hashcode=118267258
MyAnnotatedBean hashcode=1115599742
MyBean hashcode=118267258
MyAnnotatedBean hashcode=516457106

Notice that MyBean is configured to be a singleton, so the container is always returning the same instance and hashcode is always the same. Similarly, for each request, a new instance of MyAnnotatedBean is created with different hashcode.

注意,将MyBean配置为单例,因此容器始终返回相同的实例,并且哈希码始终相同。 同样,对于每个请求,将使用不同的哈希码创建MyAnnotatedBean的新实例。

基于Java的Spring Bean配置 (Java Based Spring Bean Configuration)

For standalone applications, we can use annotation based as well as XML based configuration. The only requirement is to initialize the context somewhere in the program before we use it.

对于独立应用程序,我们可以使用基于注释以及基于XML的配置。 唯一的要求是在使用程序之前在程序中的某个位置初始化上下文。

package com.journaldev.spring.main;

import java.util.Date;

public class MyService {

	public void log(String msg){
		System.out.println(new Date()+"::"+msg);
	}
}

MyService is a simple java class with some methods.

MyService是带有某些方法的简单Java类。

package com.journaldev.spring.main;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(value="com.journaldev.spring.main")
public class MyConfiguration {

	@Bean
	public MyService getService(){
		return new MyService();
	}
}

The annotation based configuration class that will be used to initialize the Spring container.

基于注释的配置类,将用于初始化Spring容器。

package com.journaldev.spring.main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyMainClass {

	public static void main(String[] args) {
		
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
				MyConfiguration.class);
		MyService service = ctx.getBean(MyService.class);
		
		service.log("Hi");
		
		MyService newService = ctx.getBean(MyService.class);
		System.out.println("service hashcode="+service.hashCode());
		System.out.println("newService hashcode="+newService.hashCode());
		ctx.close();
	}

}

A simple test program where we are initializing the AnnotationConfigApplicationContext context and then using getBean() method to get the instance of MyService.

一个简单的测试程序,我们在其中初始化AnnotationConfigApplicationContext上下文,然后使用getBean()方法获取MyService的实例。

Notice that I am calling getBean method two times and printing the hashcode. Since there is no scope defined for MyService, it should be a singleton and hence hashcode should be the same for both the instances.

注意,我两次调用了getBean方法并打印了哈希码。 由于没有为MyService定义范围,因此应为单例,因此两个实例的哈希码应相同。

When we run the above application, we get following console output confirming our understanding.

当我们运行上面的应用程序时,我们得到以下控制台输出,从而确认了我们的理解。

Sat Dec 28 22:49:18 PST 2013::Hi
service hashcode=678984726
newService hashcode=678984726

If you are looking for XML based configuration, just create the Spring XML config file and then initialize the context with following code snippet.

如果您正在寻找基于XML的配置,只需创建Spring XML配置文件,然后使用以下代码片段初始化上下文。

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        MyService app = context.getBean(MyService.class);

That’s all for the Spring IoC example tutorial, Spring Bean Scopes and Configuration details. Download the Spring IoC and Spring Bean example project from below link and play around with it for better understanding.

这就是Spring IoC示例教程,Spring Bean范围和配置详细信息的全部内容。 从下面的链接下载Spring IoC和Spring Bean示例项目,并进行试验以更好地理解。

Reference: Spring.IO Page for IOC

参考: IOC的Spring.IO页面

翻译自: https://www.journaldev.com/2461/spring-ioc-bean-example-tutorial

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值