spring系列(一)——简介和IOC

来源:互联网 发布:软件空下载 编辑:程序博客网 时间:2024/05/22 00:26

Spring简介

Spring是轻型框架,有ioc(控制反转,最常见的方式叫做依赖注入(Dependency Injection,简称DI))和aop(面向切面)两个重要功能

IOC的思路是,不用代码创建对象,而配置对象(bean),在容器加载时,加载所有对象,要使用这些对象时,从容器对象中去获得。

Spring配置使用

配置文件

Spring容器的加载需要读取Spring的配置文件,文件是xml格式,可以定义bean。一个简单的Spring配置文件test1.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.xsd">        <bean id="test" class="java.lang.String">    <constructor-arg value="张三" />    </bean></beans>
xmlns是beans的命名空间,xmlns:xsi是它的一个属性叫做xsi,xsi:schemaLocation是xml编码所要遵守的格式。

随着加载的组建/框架的增多,xmlns这里也要添加新的属性

比如要使用注解注入,就要加上

xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation编码格式中加上

http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd 
比如配置文件中要写dubbo的配置文件,就要加上

xmlns:dubbo=”http://code.alibabatech.com/schema/dubbo”
xsi:schemaLocation编码格式中加上

http://code.alibabatech.com/schema/dubbo          http://code.alibabatech.com/schema/dubbo/dubbo.xsd

如何加载Spring配置文件

java类

在普通的类中,可以通过代码的方式加载Spring的配置文件,得到Spring的容器对象,并获得容器对象中的bean对象

public class TestQ {public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("file:F:/workspace1.8/sdz-web/WebContent/WEB-INF/test1.xml");context.start();System.out.println((String)context.getBean("test"));}}
可以把代码重构一下

public class TestQ {private static ClassPathXmlApplicationContext context;static {context = new ClassPathXmlApplicationContext("file:F:/workspace1.8/sdz-web/WebContent/WEB-INF/test1.xml");context.start();}public static void main(String[] args) {System.out.println(context.getBean("test"));}}

运行结果

web

在javaweb中可以通过配置web.xml来实现Spring容器的加载,需要配置contextConfigLocation参数,值是spring配置文件,并配置spring的监听器。当项目运行时,spring监听器会加载spring的配置文件,完成容器加载。

<context-param><param-name>contextConfigLocation</param-name><param-value>WEB-INF/spring-conf.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

Bean的构造

Spring中<bean>实际上就是调用类的构造器。我给类的构造器加上打印语句,在spring中配置该类的bean,加载spring配置文件,可以发现调用了构造器的打印语句,故<bean>的实现是调用类的构造器。例子如下

Spring配置文件

<?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.xsd">    <bean id="testQ" class="com.lc.consumer.TestQ" /></beans>
Java类

public class TestQ {private static ClassPathXmlApplicationContext context;static {context = new ClassPathXmlApplicationContext("file:F:/workspace1.8/sdz-web/WebContent/WEB-INF/test1.xml");context.start();}public TestQ() {System.out.println("TestQ构造器");}public static void main(String[] args) {}}
运行结果

Bean传参赋值

Spring对象(bean)的赋值。SpringBean的属性赋值常见有两种方式property和constructor-arg,以Student类来举例。

public class Student {private String name;public Student() {}public Student(String name) {this.name = name;}public void setName(String name) {this.name = name;}}

property

property是set注入,实际上调用对象的set方法,配置标签是property。当找不到对应set方法时,会抛出异常:NotWritablePropertyException

<bean id=”stu” class=”com.lc.consumer.Student” ><property name=“name” value=”xxx”” /></bean>
等同java代码:

Student stu = new Student();stu.setName("xxx");

constructor-arg

constructor-arg是构造注入,实际上是构造器传参,配置标签是constructor-arg。

<bean id="stu" class="com.lc.consumer.Student">         <constructor-arg value="xxx" /></bean>

等同java代码:

Student stu = new Student("xxx");

同时spring支持通过factory-bean来赋值传参,下面是通过SimpleDateFormat给Date传参

<bean id="simpleDateFormat"class="java.text.SimpleDateFormat" >         <constructor-arg value="yyyy-MM-dd" /></bean><bean id="employers" class="com.lc.ioc.Employers">         <property name="workStart" >                   <bean factory-bean="simpleDateFormat" factory-method="parse">                            <constructor-arg value="2016-05-18" />                   </bean>         </property></bean>

获得bean对象

通过代码获取

普通Java类中,可通过加载配置文件得到的Spring容器上下文对象获得

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml配置地址");context.start();Student stu = (Student)context.getBean("stu");

在web项目中,可以通过request得到Spring容器上下文对象,接着根据上下文对象过的

ServletContext sc =request.getSession().getServletContext();  ApplicationContext ac1 =WebApplicationContextUtils .getRequiredWebApplicationContext(sc);ac1.getBean("stu"); 

注解注入

在实际工作中一般采用零配置的方式,完成注册bean功能。将java对象前加上'@Autowired'、'@Resource'注解,会自动在Spring容器中寻找class类型相同或class类型相同id与对象属性相同的bean,并赋值。Spring注解注入不支持静态属性。

使用方法

1.添加注入配置AutowiredAnnotationBeanPostProcessor,它的作用是查找spring容器中所有的bean,如果发现bean中存在'@Autowired'、'@Resource'注解,就根据要注入class类型,首先寻找Spring容器中是否存在相同class类型的bean:

若找到在一个,便赋值,

若找到多个,则找到id与要注入的属性名相同的bean注入

若存在多个,也没有找到id与与要注入的属性名相同的bean,它会抛出异常NoUniqueBeanDefinitionException: xxx expected single matching beanbut found 2: xxx,xxx。

注意:带注入注解的类本身必须已经注册成Spring的bean。

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

2.使用扫描注入配置<context:component-scan>,它会扫描指定包下所有的类,发现类带有'@Component'、'@Service'、'@Controller'之中的一个注解时,会自动为这个类注册bean,将所有带注解的类都注册bean之后,接着去查询所有bean,寻找'@Autowired','@Resource'注解去注入。配置它可以省略AutowiredAnnotationBeanPostProcessor配置。这里也可以加上<context:exclude-filter/>、<context:include-filter />,意思是不注册某种注解的类、只注册某种注解的类。

<context:component-scanbase-package="com.lc.consumer" />

3.使用配置<dubbo:annotation>,这是dubbo的扫描标签,与<context:component-scan>功能类似,它除了会扫描带有'@Component'、'@Service'、'@Controller'注解的类之外,它还会扫描带有”@Service”(dubbo的service标签)发布服务,它支持的注入注解除了'@Autowired','@Resource'之外,还支持'@Reference'消费服务。同样,配置<dubbo:annotation>,可以不配置<context:component-scan>,如果既配置<context:component-scan >、又配置<dubbo:annotation>,也不会注册两份bean。

<dubbo:annotationpackage="com.lc.consumer" />

0 0
原创粉丝点击