点击蓝字“程序员考拉”欢迎关注!
1.Spring依赖的jar包下载网址:
https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local/org/springframework/spring/4.0.0.RELEASE/spring-framework-4.0.0.RELEASE-dist.zip
下载之后得到:
解压在libs目录中找到如下的四个jar包:
除此之外还需要一个commons-logging.jar包。
2.例如要用spring实现如下的普通的java代码实现的功能:
HelloWorld.java
package com.java.spring;
public class HelloWorld {
private String name;
public void setName(String name){
this.name=name;
}
public void hello(){
System.out.println("hello:"+name);
}
}
Main.java
package com.java.spring;
public class Main {
public static void main(String[] args){
HelloWorld helloWorld=new HelloWorld();
helloWorld.setName("koala");
helloWorld.hello();
}
}
2.1 新建一个普通的java工程,工程目录下新建lib目录,拷贝所需的jar包:
之后build path:
2.2 在src目录下创建spring bean的配置文件:applicationContext.xml。选中项目,右击–Configure Facets–Install Spring Facet。
3.示例代码
HelloWorld.java
package com.java.spring;
public class HelloWorld {
private String name;
public void setName(String name){
this.name=name;
}
public void hello(){
System.out.println("hello:"+name);
}
}
Main.java
package com.java.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
//1.创建spring的IOC对象
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取bean实例
HelloWorld helloWorld=(HelloWorld) ctx.getBean("helloworld");
helloWorld.hello();
}
}
配置文件applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"
bean id="helloworld" class="com.java.spring.HelloWorld"
property name="name" value="koala"/property
/bean
/beans
①class的值为Bean所在的全类名;
②创建spring的IOC对象,ApplicationContext ctx=new ClassPathXmlApplicationContext(“applicationContext.xml”);参数为spring bean的配置文件的名称;
③从IOC容器中获取bean实例,HelloWorld helloWorld=(HelloWorld) ctx.getBean(“helloworld”); 配置文件中bean id=”helloworld”的值与代码中getBean(String str);方法中的str一致;
④property name=”name” value=”koala”/property 是实现public void setName(String name){ this.name=name; },将koala赋值给name属性;