IntelliJ IDEA新建maven的spring项目
IntelliJ IDEA新建maven的spring项目
pom.xml添加如下代码:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
Bean.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="org.example.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
App.java:
package org.example;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
HelloWorld.java:
package org.example;
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 org.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
//创建应用程序的上下文
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
//使用已创建的上下文的 getBean() 方法来获得所需的 bean,这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象。
HelloWorld obj = (HelloWorld) context.getBean("helloworld");
obj.getMessage();
}
}