您的位置:首页 > 编程语言 > Java开发

java中的spring框架(1)

2016-07-17 22:38 381 查看
spring框架主要有IOC编程和AOP编程

IOC大概讲的就是 对类的生成和销毁,由spring来进行管理,实际上就是第一个xml文件来进行管理,不用自己来new 一个对象 其中有一个思想就是依赖注入,就是在xml文件中 某一个类插入到另一个类中。AOP编程主要是由spring来管理开发中经常用到的日志管理和一些常用的东西等,不用自己每次都打一遍

spring框架主要有两个包,一个是spring包 还有一个是common包

创建一个普通的java项目 在其中创键lib文件夹 随后导入这些包,选中项目名,随后右键config build path 导入这些包即可

创建文件 在src下创建com.tutorialspoint类 随后创建HelloWorld.java和MainApp类 在helloWorld中编写如下代码

package com.tutorialspoint;

public class HelloWorld {
private String message;

public void getMessage() {
System.out.print("Your Message: " + message);
}

public void setMessage(String message) {
this.message = message;
}

}
随后在Beans.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-3.0.xsd"> <!--id 和 class这个是必须的 -->
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
<property name="message" value="Hello World!"/>

</bean>
<bean id = "helloIndia" class="com.tutorialspoint.HelloWorld" parent="helloWorld">

</bean>

</beans>

最核心的就是<bean></bean>中的信息 id 表明bean的类,class表示包名 随后property来设置这个类中的属性
随后在mainApp中来进行调用

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
//创建beanFactory的配置文件
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// //获取配置的上下文
// ApplicationContext context =
// new ClassPathXmlApplicationContext("Beans.xml");
// //获取bean
// HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
// obj.getMessage();
//生成工厂 得到配置文件 依赖注入来提供支持
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("Beans.xml"));
//获得所需的bean
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();

}
}

有两种方法来进行调用  第一种是获得上下文 context Beans.xml中是配置信息的文件  第二种是用BeanFactory这个类获取 不过这个类好像已经淘汰了
最后运行工程 即可成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: