spring Ioc的注解注入以及spring Aop的两种配置方式

本文详细介绍了Spring框架中的Ioc(控制反转)和Aop(面向切面编程)两大核心特性。通过实例演示了如何使用注解配置Bean、注入属性及依赖,并展示了Aop在增强代码复用性和维护性方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.spring Ioc的注解注入

    1.1 导包

        

    1.2 导入约束

    

          

      1.3 选择使用注解的包

            

      1.4 在类中使用注解配置bean

                User类

// <bean name="user" class="domain.User"></bean>
@Component("user")
	/*@Service("user")//service层
	@Controller("user")//web层
	@Repository("user")//dao层
	 */
//指定对象作用范围
//@Scope(scopeName="prototype")
public class User {
	@Value("mengyue")//为属性注入值
	private String name;
	@Value("21")
	private Integer age;
	
//	@Autowired //自动装配  多个对象时  无法选择
//	@Qualifier("car")  //告诉spring容器 装配哪个名称的对象
	@Resource(name="car") //手动注入名称为 car的对象
	private Car car;
	
	@PostConstruct //指明在构造方法之后调用该方法  相当于 init-method
	public void init(){
		System.out.println("我是初始化方法。");
	}
	@PreDestroy //指明在对象销毁之前调用该方法 相当于 destory-method
	public void destroy(){
		System.out.println("我是销毁方法。");
	}
                Car类
@Component("car")
public class Car {
	@Value("法拉利488")
	private String name;
	@Value("白色")
	private String color;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public Car() {
	}
	public String toString() {
		return "Car [name=" + name + ", color=" + color + "]";
	}
	
}
            测试类


//创建容器
/*@RunWith(SpringJUnit4ClassRunner.class)  
//指定创建容器时加载哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")*/
public class demo {
	/*@Resource(name="user")
	private User u;*/
	@Test
	public void test1(){
		ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
		User user=(User) applicationContext.getBean("user");
		System.out.println(user);
		
	}

               运行结果


2.spring Aop

    2.1 spring Aop的介绍

            Aop是一种面向切面编程的思想,将重复的代码 抽取出来 切入到流程当中。spring 实现Aop的原理是运用了动态代理和cglib代理。动态代理是JDK自带的代理技术,要求被代理对象必须要实现接口,才能产生代理对象,如果没有接口,就不能使用动态代理技术。cglib是一种第三方代理技术,可以对任何类生成代理,cglib进行代理的原理是,对目标对象进行继承,所以当目标对象被final修饰时,该类无法被代理。

            在选择上,spring会优先选择动态代理,如果动态代理没法满足,就会采用cglib代理。


    Aop中的术语:Joinpoint(连接点) :目标对象可以被增强的方法

                             Pointcut(切入点):目标对象,需要增强的方法

                             Advice(通知):增强代码

                             Target(目标对象):被代理的对象

                              Weaving(织入):将通知织入切入点

                               Proxy(代理):完成织入之后,产生代理对象

                               aspect(切面):切入点+通知

                               

2.2.spring Aop配置

       首先使用注解的方式配置

    2.2.1 导包

           

            

    2.2.2  导入约束


     2.2.3 配置文件

      

      2.2.4 目标对象

package service;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService{

	public void save() {
		System.out.println("增加用户");
	}

	public void delete() {
		System.out.println("删除用户");
		
	}

	public void update() {
		System.out.println("修改用户");
		
	}

	public void find() {
		System.out.println("查找用户");
		
	}
	

}

          2.2.5 通知

            

package aspects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("myAdvice")
// 告诉spring 该类为通知对象
@Aspect
public class MyAdvice {
	@Pointcut("execution(* service.*ServiceImpl.*(..))")
	public void pointCut(){}
	
	
	//指定前置通知  并指定切点
	@Before("MyAdvice.pointCut()")
	public void before(){
		System.out.println("这是前置通知!");
	}
	@AfterReturning("MyAdvice.pointCut()")
	public void afterReturning(){
		System.out.println("这是后置通知,抛出异常时不执行!");
	}
	@Around("execution(* service.*ServiceImpl.*(..))")
	public Object around(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("这是前置通知!");
		Object proceed = pjp.proceed();
		System.out.println("这是后置通知!");
		return proceed;
		
	}
	@AfterThrowing("execution(* service.*ServiceImpl.*(..))")
	public void exception(){
		System.out.println("有异常哦!");
	}
	@After("execution(* service.*ServiceImpl.*(..))")
	public void after(){
		System.out.println("这是后置通知,抛出异常时依然执行!");
	}

}
            

             2.2.6 测试类

@Test
	public void test3(){
		ApplicationContext applicationContext= new ClassPathXmlApplicationContext("demo/applicationContext.xml");
		UserService userService=(UserService) applicationContext.getBean("userService");
		userService.find();
		
	}


    xml的方式进行配置

                

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://www.springframework.org/schema/beans" 
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
	<!--1.应用注解-->
	<context:component-scan base-package="domain"></context:component-scan>
	<!-- springAop的配置 -->
	<!-- 1.配置目标对象 -->
	<bean name="userService" class="service.UserServiceImpl"></bean>
	<!--2.配置通知对象 -->
	<bean name="myAdvice" class="aspects.MyAdvice"></bean>
	<!--3.将通知织入到目标对象  -->
	<aop:config>
		<!--3.1.配置切点  -->
		<aop:pointcut expression="execution(* service.*ServiceImpl.*(..))" id="pc"/>
		<!--3.2.配置切面 -->
		<aop:aspect ref="myAdvice">
			<aop:before method="before" pointcut-ref="pc"/>
			<aop:after-returning method="afterReturning" pointcut-ref="pc"/>
			<aop:around method="around" pointcut-ref="pc"/>
			<aop:after-throwing method="exception" pointcut-ref="pc"/>
			<aop:after method="after" pointcut-ref="pc"/>
		</aop:aspect>
	</aop:config>
</beans>
    


            

       






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值