读书人

Spring 诠注的配置的细节

发布时间: 2012-09-20 09:36:51 作者: rapoo

Spring 注解的配置的细节

<beans?其中base-package 为需要扫描的包(包含子包)
(3)
@Service用于标注业务层组件
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件 ,即DAO 组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

(4)
业务类
@Service
public class PersonServiceBean implements PersonService {.....}
输出类
AbstractApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService= (PersonService)cxt.getBean("personServiceBean");
System.out.println(personService);
cxt.close();
使用注解中bean的id默认名称为类名称的首字母小写名称
--------------------------------------------------
自己指定名称
@Service("aa") //默认作用域范围 是单例范围
public class PersonServiceBean implements PersonService {.....}
输出类
AbstractApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService= (PersonService)cxt.getBean("aa");
System.out.println(personService);
cxt.close();
--------------------------------------------------
@Service("aa") @Scope("prototype")//修改bean的作用域
public class PersonServiceBean implements PersonService {....}


-----------------------
?? @PostConstruct<beans?将切面和被拦截的类交给spring管理
(3)切面类

@Aspect //定义切面类
public class MyInterceptor {
?? /**
??? *? @Pointcut("execution(* com.hf.service..*.*(..))")表达式含义
??? * 第一个* 表示返回值类型为任意类型
??? * com.hf.service..? 两个点表示包路径下的子包的类也要拦截
??? * com.hf.service..*.* 子包的所有类中的所有方法 第一个*是方法第二个*是类
??? * (..)代表方法参数随意 可有可无可多可少
??? * **/

?? @Pointcut("execution (* com.hf.service.impl.PersonServiceBean.*(..))")// 定义切入点
?? private void andMethod()//声明一个切入点?? public void doAfterThrowing(Exception e){???
??? System.out.println("例外通知:"+e);
?? }
???
???
?? @Around("andMethod()")//环绕通知
?? public Object doBasecProfiling(ProceedingJoinPoint pjp )throws Throwable{
?? //if(){//判断是否与权限
??? System.out.println("进入通知");
??? Object result = pjp.proceed();
??? System.out.println("离开 通知");
?? //}
??? return result;
????
????
?? }
}

(4)业务类 PersonServiceBean?
public class PersonServiceBean implements PersonService {

?public void save(String name){
????? throw new RuntimeException("纯属例外");
????? // System.out.println("我是Save方法"+name);
??? }
?public String update() {??
? return "我是update方法";
?}
}

读书人网 >软件架构设计

热点推荐