一 创建一个普通的javaproject
工程的目录结构如下:
二 不使用spring的情况
package com.lisx.spring.beans;
public class Main {
public static void main(String[] args) {
// new一个对象
HelloWorld helloWorld = new HelloWorld();
helloWorld.print();
}
}
输出结果:
HelloWorld0
三 使用spring创建bean
1:必须下载五个jar包才行
a: commons-logging-1.1.1.jar我是到maven中央仓库中去下载的,下载地址为
https://repo.maven.apache.org/maven2/commons-logging/commons-logging/1.1.1/
b: 剩下4个jar包是到spring官网下载的
http://projects.spring.io/spring-framework/
2:创建spring-bean1.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="com.lisx.spring.beans.HelloWorld">
<property name="age" value="10000"></property>
</bean>
</beans>
3:main.java
package com.lisx.spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// 使用spring创建bean
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-bean1.xml");
HelloWorld helloWorld1 = (HelloWorld) ctx.getBean("helloWorld");
helloWorld1.print();
}
}
4:输出结果
五月 13, 2018 11:28:49 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@230c34a9: startup date [Sun May 13 23:28:49 CST 2018]; root of context hierarchy
五月 13, 2018 11:28:49 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-bean1.xml]
HelloWorld10000
不仅输出结果,还输出了日志。并且在创建spring-bean1.xml文件时还修改了bean的值。