Spring注解实现装配

常见注解基本装配
@Conponent 默认id就是类名
@Controller 表示层
@Service 业务逻辑层
@Repository 数据持久层

注入:
xml:手工注入(设值注入,构造注入)
自动注入

applicationContext:

ontext:component-scan base-package="dao"></context:component-scan>

作用:扫描配置了注解的对象 将他注册为Spring的bean放置在ioc容器中

在接口实现类的头部 写上:

@Repository("userdao")

注解注入:
1)@Autowired:按类型注入
2)@Autowired
@Qualifier(“id”):按照名称注入
3)Resources(name=“id”) 按名称注入

增强代码类(切面类)

@Component
@Aspect     //切面类(切入点和增强代码)
public class MyAdvice {
	//环绕增强直接拦截所有方法    需要手动调用方法
	public void around(ProceedingJoinPoint joinpoint) {
		try {
			System.out.println("前置增强");
			joinpoint.proceed();
			System.out.println("后置增强");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("异常增强");
		}finally {
			System.out.println("最终增强");
		}
	}
	@Pointcut("execution(* service.impl.UserServiceImpl.*(..))")
	public void pointcut() {}
	
	@Before("pointcut()")
	public void before() {
		System.out.println("前置增强");
	}
	
	@AfterReturning("pointcut()")
	public void afterreturning() {
		System.out.println("后置增强");
	}
	@AfterThrowing("pointcut()")
	public void afterthrowing() {
		System.out.println("异常增强");
	}
	@After("pointcut()")
	public void after() {
		System.out.println("最终增强");
	}	
}

service对象声明类,委托类

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

	@Override
	public void addUser() {
		// TODO Auto-generated method stub
		System.out.println("添加");
	}

	@Override
	public void deleteUser() {
		// TODO Auto-generated method stub
		System.out.println("删除");
	}
	
}

xml文件中进行包的注解扫描和切面配置的注解生效

    <context:component-scan base-package="myadvice,service"></context:component-scan>
    <aop:aspectj-autoproxy />     <!-- 切面配置的注解生效 -->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值