Java如何在Spring应用程序中声明bean?
在这个例子中,我们将学习如何在SpringApplication中声明一个bean。我们将构建一个简单的Maven项目来演示它。因此,让我们开始设置我们的Maven项目。
创建一个Maven项目
下面是我们的Maven项目的目录结构。
.
├── pom.xml
└── src
└── main
├── java
│ └── org
│ └── nhooo
│ └── example
│ └── spring
│ └── hello
│ ├── Hello.java
│ ├── HelloImpl.java
│ └── HelloWorldDemo.java
└── resources
└── spring.xml配置Mavenpom.xml文件
我们需要创建一个pom.xml文件,并添加项目配置和库依赖项。
<?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">
<parent>
<artifactId>nhooo-project</artifactId>
<groupId>org.nhooo.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nhooo-spring-core</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.2.RELEASE</version>
</dependency>
</dependencies>
</project>创建一个Bean
接下来,我们将创建一个名为的简单beanHelloImpl。该bean实现了一个接口Hello,该接口用一个sayHello()要实现的方法调用。这是接口的实现定义。
package org.nhooo.example.spring.hello;
public interface Hello {
void sayHello();
}package org.nhooo.example.spring.hello;
public class HelloImpl implements Hello {
public void sayHello() {
System.out.println("Hello World!");
}
}在SpringConfiguration中注册Bean
拥有bean之后,我们需要创建Spring配置,它是一个xml文件,我们将其命名为spring.xml。使用bean配置文件中的元素声明的Bean。声明至少包含bean的id和class。
<?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="hello"/>
</beans>在我们的应用程序中使用Bean
现在,我们在Spring容器中声明了bean。下一步将向您展示如何从容器中获取bean并在我们的程序中使用它。有很多方法可以用来加载Spring容器。在这里,我们将使用ClassPathXmlApplicationContext。此类加载在运行时类路径中找到的配置。
package org.nhooo.example.spring.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldDemo {
public static void main(String[] args) {
String config = "spring.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(config);
Hello hello = (Hello) context.getBean("hello");
hello.sayHello();
}
}