Spring框架解析二【注解】

来源:互联网 发布:动感新时代淘宝 编辑:程序博客网 时间:2024/05/29 18:23

Mybatis注解

@SelectProvider是声明在方法基本上的,这个方法定义在Mapper对应的的interface上。

1 public interface UserMapper {
2     @SelectProvider(type = SqlProvider.class, method = "selectUser")
3     @ResultMap("userMap")
4     public User getUser(long userId);
5 }
上例中是个很简单的Mapper接口,其中定义了一个方法:getUser,这个方法根据提供的用户id来查询用户信息,并返回一个User实体bean。
这是一个很简单很常用的查询场景:根据key来查询记录并将结果封装成实体bean。其中:
@SelectProvider注解用于生成查询用的sql语句,有别于@Select注解,@SelectProvide指定一个Class及其方法,并且通过调用Class上的这个方法来获得sql语句。在我们这个例子中,获取查询sql的方法是SqlProvider.selectUser。
@ResultMap注解用于从查询结果集RecordSet中取数据然后拼装实体bean。

@Entity

@Entity@Table(name = "data_source")public class DataSource implements Serializable {   private static final long serialVersionUID = -1912844803103688659L;   @Id   @Column(name = "id")   private String id;   @Column(name = "db_name")   private String dbName;   @Column(name = "db_type")   private String dbType;

@Document

@Inherit

@Target

@Role


@Configuration

@Bean

@Component

@Repository

@Service

@Controller

@RestController


@Scope

singleton便是容器默认的scope。Spring容器最初提供了两种bean的scope类型:singleton和 prototype,但发布2.0之后,又引入了另外三种scope类型,即request,session和global session类型。不过这三种类型有所限制,只能在web应用中使用,也就是说,只有在支持web应用的ApplicationContext中使用这 三个scope才是合理的。

@RequestMapping

@Param

@PathVariable
/** * 进入首页 * @param req * @param resp */@RequestMapping(value = {"index/{configId}"})public ModelAndView index(@PathVariable String configId,HttpServletRequest req,HttpServletResponse resp){   String webPage =  staticPageService.applyIndexPage();   String newPage = checkUser(req,resp,webPage,configId);   return toPage(newPage);}  
@RequestBody
@RequestParam
@ResponseBody
@RequestMapping(value = "update/{id}", method = RequestMethod.GET)public @ResponseBody TaskInfo  updateForm(@PathVariable("id") String id, Model model) {

@ModelAttribute
@Deprecated@RequestMapping("/store/activate")@RestControllerpublic class ActivateController {    private Logger logger = LoggerFactory.getLogger(ActivateController.class);    @RequestMapping(value={"/", ""})    @ResponseBody    public Object revOpenMsg(@ModelAttribute StoreOrderAccessEntity storeOrderAccessEntity, HttpServletRequest request) throws Exception {        if (logger.isDebugEnabled()) {            Enumeration<String> params = request.getParameterNames();            while (params.hasMoreElements()) {                String param = params.nextElement();                logger.debug("云市场激活推送:参数{}==={}", param, request.getParameter(param));            }        }        //HttpUtils        return null;    }}

@Autowired

@Resource

@Value

@PostConstruct和@PreDestory

--声明式事务

@Transactional

@Aspect 

@Aspectpublic class DataSourceAspect {   private Logger log = LoggerFactory.getLogger(DataSourceAspect.class);// @Autowired// private SessionManager sessionMgr;   /**    * 必须为final String类型的,注解里要使用的变量只能是静态常量类型的    */   public static final String EDP = "execution(* com.*.uap.ieop.security.service..*.*(..))" + " || "         + "execution(* iu.portal.service..*.*(..))" + " || " + "execution(* com.*.uap.wb.service..*.*(..))"         + " || " + "execution(* com.*.uap.wb.service.impl..*.*(..))" + " || "         + "execution(* iu.portal.runtime.service..*.*(..))" + " || "         + "execution(* com.*.uap.wb.web.controller..*.*(..))";   @Before(EDP)   public void setDateSource(JoinPoint point) {      String tenantId = InvocationInfoProxy.getTenantid();      DbContextHolder.setDBType(tenantId);   }   @After(EDP)   public void afterSetdataSource(JoinPoint point) {   }   @Around(EDP)   public Object aroundSetDataSource(ProceedingJoinPoint joinPoint)  {      Object[] args = joinPoint.getArgs();      Object obj = null;      try {         obj = joinPoint.proceed(args);      } catch (Throwable e) {          log.error(e.getMessage(), e);      }      return obj;   }}

AOP注解实现示例:

  1. @Aspect  
  2. public class MyInterceptor {  
  3.     @Pointcut("execution(* com.bird.service.impl.PersonServiceBean.*(..))")  
  4.     private void anyMethod(){}//定义一个切入点  
  5.       
  6.     @Before("anyMethod() && args(name)")  
  7.     public void doAccessCheck(String name){  
  8.         System.out.println(name);  
  9.         System.out.println("前置通知");  
  10.     }  
  11.       
  12.     @AfterReturning("anyMethod()")  
  13.     public void doAfter(){  
  14.         System.out.println("后置通知");  
  15.     }  
  16.       
  17.     @After("anyMethod()")  
  18.     public void after(){  
  19.         System.out.println("最终通知");  
  20.     }  
  21.       
  22.     @AfterThrowing("anyMethod()")  
  23.     public void doAfterThrow(){  
  24.         System.out.println("例外通知");  
  25.     }  
  26.       
  27.     @Around("anyMethod()")  
  28.     public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{  
  29.         System.out.println("进入环绕通知");  
  30.         Object object = pjp.proceed();//执行该方法  
  31.         System.out.println("退出方法");  
  32.         return object;  
  33.     }  
  34. }  

0 0
原创粉丝点击