首页 > 代码库 > Spring笔记

Spring笔记

Spring的框架组成:它是对web层、业务层、数据访问层的每层都有解决方案;web层:Spring MVC;持久层:JDBC Template ;业务层:Spring的Bean管理;

技术分享

 一、核心部分之IOC

技术分享

实例;接口:HelloService.java 

技术分享
public interface HelloService {
    public void sayHello();
}
View Code

 接口实现类:HelloServiceImpl.java

技术分享
public class HelloServiceImpl implements HelloService {
    private String info;
    
    public void setInfo(String info) {
        this.info = info;
    }

    public void sayHello() {
        System.out.println("Hello Spring..."+info);
    }

}
View Code

 配置文件:applicationContext.xml

技术分享
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd">

    <!-- 通过一个<bean>标签设置类的信息,通过id属性为类起个标识. -->
    <bean id="userService" class="cn.itcast.spring3.demo1.HelloServiceImpl">
        <!-- 使用<property>标签注入属性 -->
        <property name="info" value="传智播客"/>
    </bean>
        
</beans>
View Code

 测试: SpringTest1.java 

技术分享
public class SpringTest1 {

    @Test
    // 传统方式
    public void demo1() {
        // 造成程序紧密耦合.
        HelloService helloService = new HelloServiceImpl();
        helloService.sayHello();
    }

    @Test
    // Spring开发
    public void demo2() {
        // 创建一个工厂类.
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        HelloService helloService = (HelloService) applicationContext
                .getBean("userService");
        helloService.sayHello();
    }

    @Test
    // 加载磁盘路径下的配置文件:
    public void demo3() {
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
                "applicationContext.xml");
        HelloService helloService = (HelloService) applicationContext
                .getBean("userService");
        helloService.sayHello();
    }
    
    @Test
    public void demo4(){
        // ClassPathResource  FileSystemResource
        BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml"));
        HelloService helloService = (HelloService) beanFactory.getBean("userService");
        helloService.sayHello();
    }
}
View Code

 

Spring笔记