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

Spring(FirstDay)

2015-10-24 00:15 405 查看
1.Spring概念:Spring是一个开源的IOC和AOP容器框架。主要目的是简化企业开发

2.所谓IOC(inversion of control)控制反转就是应用程序本身不负责依赖对象的创建和维护,将权利交给外部容器。这种权利的转黄就叫做反转

3.第一个Spring程序:

3.1)配置文件编写,spring配置文件名称没有限制,默认为applicationContext.xml,通常放置在类路径下面,配置文件头的编写,可以参考官网spring.io--->上面的说明文档。

模板代码如下:<?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-2.5.xsd"> </beans>

  3.2)初始化spring容器:主要API 

接口:BeanFactory-->子接口ApplicationContext(常用)-->实现类ClassPathXmlApplicationContext、FileSystemXmlApplicationContext

 3.3)spring管理及维护对象配置:

     3.3.1)配置文件编写对应类的无参构造器进行配置:

<bean id="xx" class="xx"></bean>

其中:id 为唯一标识符,唯一标识一个对象,class及想要维护的对象所属的类

   3.3.2)Java只要代码

ApplicationContext ac=new ClassPathXmlApplicationContext("配置文件路径");

ac.getBean("id的值");//得到对应配置文件中对应id的对应类的对象

4.整体代码:

//一个需要维护的类

public class FirstBean {
public void f(){
System.out.println("你好");
}

}

//测试方法编写

public class springFirstDAy {
@Test
public void f(){

ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");
FirstBean f=(FirstBean)ac.getBean("one");//获得FirstBean的对象,由于ac.getBean()返回Object类型,所以进行强制转换
f.f();
}

}

//配置文件

<?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-2.5.xsd"> <bean id="one" class="main.FirstBean"></bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring