Spring01

通过配置applicationContext.xml文件来获取类对象以及参数

实例:

步骤1:在com.hello.dao包下新建一个接口UserDao以及它的实现类UserDaoImpl

UserDao接口:

package com.hello.dao;

public interface UserDao {

        public void login(String name,String pass);

}

UserDaoImpl实现类:

package com.hello.dao;

public class UserDaoImpl implements UserDao {

        @Override

        public void login(String name, String pass) {

                System.out.println("用户名:"+name+"  密码:"+pass);

        }

}

步骤2:在com.hello.service包下新建一个接口UserService以及它的实现类UserServiceImpl

UserService接口:

package com.hello.service;

public interface UserService {

        public void login(String name,String pass);

}

UserServiceImpl实现类:

package com.hello.service;

import com.hello.dao.UserDao;

public class UserServiceImpl implements UserService {

        // 1. 添加字段(字段名要和applicationContext.xml中的一样)

        private UserDao userDao;

        // 2. 添加字段的 setter() 方法(一定要有,要不然userDao为null)

        public void setUserDao(UserDao userDao) {

                this.userDao = userDao;

        }

        //3.在xml文件中需要把初始化的对象,ref 到指定的类中

        @Override

        public void login(String name, String pass) {

                userDao.login(name,pass);

        }

}

步骤3:在src下新建一个xml文件applicationContext.xml

applicationContext.xml配置如下:


    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">

        

上面的property为参数注入,参数注入需要set方法来初始化,还有一个构造器注入constructor,构造器注入和参数注入差不多,区别就是构造器注入不需要set方法,而是需要有一个有参构造方法来初始化。

步骤4:最后一个步骤就是测试了,新建一个测试类TestClass

package com.hello.test;

import org.junit.Test;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hello.service.UserService;

public class TestClass {

@Test

public void test(){

// 获取 Spring 容器 --- BeanFactory

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

//获取bean

UserService us = (UserService) factory.getBean("UserService");

us.login("陈赞", "1234");

}

}

就两个步骤,获取Spring容器+获取需要用的bean就可以拿到需要用的一个对象了

*然后还有一个获取Spring 容器的方式,也就是读取applicationContext.xml的方法:

方式②BeanFactory factory = new xmlBeanFactory(new ClassPathResoure("applicationContext.xml"))

这个方式跟上面那个方式①BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml") 的区别是什么呢??

方式①:在自身被实例化时一次性完成所有Bean的创建,所以在服务启动的时候就会校验xml文件的正确性

方式②:采用的是延迟加载,知道第一次使用getBean()方法的获取Bean实例时才会创建相对应的Bean,在服务器启动时不会校验xml文件的正确性,知道获取bean时,如果装配错误马上就会产生异常(不受其它bean的影响)

简单的说就是如果采用方式①,执行xml文件时只要随便一个bean装配有错误都会报错;而采用方式②时,执行xml文件不会去校验正确性,只有getBean的时候对应的bean装配有错误时才会报错。

你可能感兴趣的:(Spring01)