龙空技术网

Spring IOC容器Java配置示例

江上孤舟sky 48

前言:

现时你们对“给spring容器提供配置元数据”大体比较注重,姐妹们都需要了解一些“给spring容器提供配置元数据”的相关知识。那么小编同时在网上收集了一些有关“给spring容器提供配置元数据””的相关文章,希望姐妹们能喜欢,同学们一起来学习一下吧!

在本文中,我们将通过一个简单的示例,来演示基于java配置元数据的Spring IOC 容器。

Spring IOC容器负责实例化,配置和组装Spring Bean。容器通过读取配置元数据来获取要实例化,配置和组装哪些对象的信息。配置元数据以XML,Java注释或Java配置的形式表示。它使您能够表达组成应用程序的对象以及这些对象之间的相互依赖关系。

Spring IoC容器提供了三种方式配置元数据

基于XML的配置基于注释的配置基于Java的配置

在此示例中,我们将向Spring IoC容器提供基于Java配置元数据。

Spring应用程序开发步骤创建Maven项目添加Maven依赖项配置 Spring Beans创建spring容器从Spring容器中获取Bean1.创建Maven项目

使用您喜欢的IDE创建一个maven项目,本项目使用IDEA开发工具创建。

2.添加Maven依赖项

        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>5.1.0.RELEASE</version>        </dependency>         
3.配置 Bean

通常,Spring bean是由Spring容器管理的Java对象。

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

配置元数据

package com.spring.ioc.helloworld;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class AppConfig {    @Bean    public HelloWorld helloWorld() {        HelloWorld helloWorld = new HelloWorld();        helloWorld.setMessage("Hello World!");        return helloWorld;    }}

Spring @Configuration注释是spring核心框架的一部分。Spring Configuration注释表示该类具有@Bean定义方法。因此,Spring容器可以处理类并生成应用程序中使用的Spring bean。

4.创建spring容器

package com.spring.ioc.helloworld;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Application {    public static void main(String[] args) {        AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);        context.close();    }}
5.从Spring容器中获取Bean

ApplicationContext接口提供getBean()方法以从Spring容器中获取bean。

package com.spring.ioc.helloworld;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Application {    public static void main(String[] args) {        // ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");        obj.getMessage();        context.close();    }}

输出

My Message : Hello World!

想获取源码请私信我获取!更多资源请参考:

标签: #给spring容器提供配置元数据 #如何给spring容器提供配置元数据