从今天开始,我们学习Spring框架的使用。
从我的理解来说,spring就像一个容器,什么东西都可以装。
这样说有点笼统,我们先一点一点来学。
首先先说像对象的创建,我们需要new一个对象,但如果使用spring,我们就可以把对象的创建交给spring,用spring的方法来
来获取对象,老惯例,我们来打印一个‘helloworld’
首先是spring的几个核心包:
先新建一个类:
package com.fei.HelloOne;
public class HelloWorld {
private String name;
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "HelloWorld [name=" + name + "]";
}
public void printHelloWorld() {
System.out.println("helloworld");
}
}
public void printHelloWorld() {
System.out.println("helloworld");
}
一个方法输出helloworld
现在我们用在src下新建一个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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
</bean>
<bean name = "helloWorld" class="com.fei.HelloOne.HelloWorld"
p:name="world" p:price="2333" scope="prototype">
</bean>
</beans>
然后在main函数试试输出:
public static void main(String[] args) {
ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld hw=(HelloWorld) ac.getBean("helloWorld");
hw.printHelloWorld();
}
输出结果:
三月 10, 2018 6:42:19 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
三月 10, 2018 6:42:19 下午 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
信息: Loading properties file from class path resource [db.properties]
三月 10, 2018 6:42:20 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
三月 10, 2018 6:42:21 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
helloworld
前面不用看,使我们的输出日志,最后我们的‘helloworld’已经打印出来了!