В pom.xml добавить зависимость на Spring фреймвокр:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
</dependencies>
В папке Java создать файл Message.java с классом бина:
public class Message {
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
и файл App.java:
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main (String[] args)
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Message message = (Message) context.getBean("helloWorld");
System.out.println(message.getMessage());
}
}
В папке resources создать файл applicationContext.xml с описанием бина:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean class="Message" id="helloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
или
<?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 class="Message" id="helloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
Проект выглядит так:
Бин создаётся с помощью описания в XML. С версии 3.0 можно бин создавать программно.