Spring学习之路(一)

2017-07-18  本文已影响0人  秋灯锁忆

使用Spring的原因


Spring的运用范围

spring可包含这四层,bean间配置可以体现层与层间的关联关系

运用范围

入门案例

HelloService.java

package com.service;

public class HelloService {
    private String name;
    private BybService bybService;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public BybService getBybService() {
        return bybService;
    }

    public void setBybService(BybService bybService) {
        this.bybService = bybService;
    }

    public void sayhello(){
        System.out.print("hello"+name);
        bybService.sayBybe();
    }
}

BybService.java

package com.service;

public class BybService {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void sayBybe(){
        System.out.print("bybe"+name);
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<!--引入schema规范文件-->
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!--配置bean,id为该HelloService的别名,与其对应;class为类路径-->
<bean id="helloService" class="com.service.HelloService">
<!--数据注入,对该属性赋值-->
    <property name="name">
        <value>小明</value>
    </property>
<!--关系注入,形成依赖,前者bybService为HelloService.java属性值,后者bybService为 该文件配置BybService的id-->
    <property name="bybService" ref="bybService">
    </property>
</bean>
<bean id="bybService" class="com.service.BybService">
    <property name="name" value="小明"></property>
</bean>
</beans>
package com.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//创建容器对象,该句执行后,加载容器中所有bean(当然仅对上述配置的bean),预先加载,不管你是否会使用。
//ClassPathXmlApplicationContext("applicationContext.xml");指明配置文件的名称与路径,请自行更改调整。
        HelloService us=(HelloService)ac.getBean("helloService");
        BybService by=(BybService)ac.getBean("bybService");
//获取已加载的对应类对象,使用函数getBean(id),同时注意类型转换。
        us.sayhello();
        by.sayBybe();   
//调用对象函数。   
    }
}

上一篇下一篇

猜你喜欢

热点阅读