实训day04-Spring框架

2061 0

Spring框架

一、控制反转(IOC)生成对象

《spring使用入门》

文档:spring官网 -> 右上角progects -> spring framework -> learn 标签 -> xxx refrence…

【基本功能 IOC 容器 III.7】

普通对象的生成——Student相关示例

导入资源:spring-context

pom.xml:

<!– https://mvnrepository.com/artifact/org.springframework/spring-context –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>

1.写一个配置文件用于设计如何生成一个对象:

spring.xml:

<beans     xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xmlns=”http://www.springframework.org/schema/beans”

xmlns:context=”http://www.springframework.org/schema/context”

xsi:schemaLocation=”    http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd ” ></beans>

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-instantiation

在程序中生成一个spring IOC 容器(context),它类似于工厂:ApplicationContext context=new ClassPathXmlApplicationContext(“源代码文件夹下的配置文件路径”);

eg:ApplicationContext context=new ClassPathXmlApplicationContext(“spring.xml”);

使用容器获取你需要的对象。

Student s=context.getBean(“S1″,Student.class);

注意:使用默认方式生成的对象,都是单例的。如果你希望每次都生成一个新的对象,那么在bean标签中加入:scope=”prototype”

对对象属性进行赋值,如果是基本类型或String,使用:<property name=”属性名” value=”属性值”/>。
对非基本类型赋值:<property name=”属性名” ref=”对象ID”></property>

<bean id=”S1″ class=”xujoe.day04_Maven.MC.Server.People”>

<!– collaborators and configuration for this bean go here –>

<property name=”name” value=”小明”></property>

<property name=”sex” value=”男”></property>

<property name=”age” value=”11″></property>

</bean>

 

2.有参构造方法对象的生成——Car
<constructor-arg value=”参数值” name=”参数名”></constructor-arg>

3.自动包扫描——Service&GetTimer
<context:component-scan base-package=”你要扫描的包”></context:component-scan>
该包下需要被扫描的对象必须有@Component注解。

4.对于一些功能对象,可以直接注入到使用者的属性上,这叫自动注入。前提:被注入者和注入者都要是由spring管理的。
需要注入的属性标识上加入@Autowired注解即可自动注入一个存在于spring容器中的、符合条件的对象。

二、面对切面编程(AOP)

文档:https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/htmlsingle/#aop-ataspectj

1、导入切面织入引擎:AspectJ-weaver(通过http://mvnrepository.com/search?q=AspectJ-weaver下载或者直接粘贴到pom.XML文件)
2、在配置文件中加入一个切面注解标签<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
3、编写切面类,该类必须由spring IOC 容器管理,且有@Aspect注解
4、编写切面方法,该方法使用一个顺序注解(例如@After)注解并需要指定运行规则:
https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/htmlsingle/#aop-pointcuts-examples

5、正常执行,要求:被切的切点方法所属于的对象本身也要由spring生成。

6、在切面方法中获取切点方法的参数:
1,在切面方法的参数列表中加入JoinPoint对象
2,使用该对象的getArgs()获取切点方法的传入参数,从0号开始计数,它是一个Object[]。

7、使用环绕式包围切点:
@Around注解,并在参数列表中加入ProceedingJoinPoint对象的声明。
proceed(args)执行原始的切点方法,传入的参数就是执行参数,返回的参数就是原始切点方法返回的参数。
该切面方法的返回值将作为最终返回值来用。

 

 

 

 

 

发表回复