Spring--Spring和Spring Boot的注解区别

2018-07-18  本文已影响0人  栗子酥小小

Spring注解

@Resource(name=”userDao”)  
private UsreDao userDao;  
@Configuration  
public class ExampleConfiguration {  
  
    @Value("com.mysql.jdbc.Driver")  
    private String driverClassName;  
  
    @Value("jdbc://xxxx.xx.xxx/xx")  
    private String driverUrl;  
  
    @Value("${root}")  
    private String driverUsername;  
  
    @Value("123456")  
    private String driverPassword;  
  
    @Bean(name = "dataSource")  
    public DataSource dataSource() {  
        BasicDataSource dataSource = new BasicDataSource();  
        dataSource.setDriverClassName(driverClassName);  
        dataSource.setUrl(driverUrl);  
        dataSource.setUsername(driverUsername);  
        dataSource.setPassword(driverPassword);  
        return dataSource;  
    }  
  
    @Bean  
    public PlatformTransactionManager transactionManager() {  
        return new DataSourceTransactionManager(dataSource());  
    }  
  
}
// 使用:
@Autowired
private DataSource dataSource;

// 此外,@Configuration 也可以去注册@Component的Bean,不过要用@ComponentScan()同时标注好要扫描的包,而包下面有@Componen注解的类才行。
// 再此外,@Configuration还可以和@ImportResource("classpath:applicationContext-configuration.xml")组合载入xml文件配置
// 假设.properties文件如下:
test.name=cy
test.port=8090
test.servers[0]=dev.bar.com
test.servers[1]=foo.bar.com
// 对应调用类如下:
@ConfigurationProperties(prefix="test")
public class Config {
    private String name;
    private Integer port;
    private List<String> servers = new ArrayList<String>();

    public String geName(){
        return this.name;
    }

    public Integer gePort(){
        return this.port;
    }
    public List<String> getServers() {
        return this.servers;
    }
}

@Component
@ConfigurationProperties(prefix = "test")
@PropertySource("classpath:test.properties")
补充:属性间可以用${}来引用前面的变量。
补充2:属性匹配规则:如果变量是firstName,则属性名可以是
1:person.firstName,标准的驼峰式命名,
2:person.first-name,虚线(-)分割方式,推荐在.properties和.yml配置文件中使用,
3:PERSON_FIRST_NAME,大写下划线形式,建议在系统环境变量中使用
@RequestMapping("/login.do")
    @ResponseBody
    public Object login(String name, String password, HttpSession session) {
        user = userService.checkLogin(name, password);
        session.setAttribute("user", user);
        return new JsonResult(user);
    }
@RequestMapping("/login.do")
    @ResponseBody
    public Object login(@RequestBody User loginUuser, HttpSession session) {
        user = userService.checkLogin(loginUser);
        session.setAttribute("user", user);
        return new JsonResult(user);
    }
@Controller 
@RequestMapping("/owners/{a}") 
public class RelativePathUriTemplateController { 
  @RequestMapping("/pets/{b}") 
  public void findPet(@PathVariable("a") String a,@PathVariable String b, Model model) {     
    // implementation omitted 
  } 
}
@RequestMapping("/test") 
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, 
                              @RequestHeader("Keep-Alive")long keepAlive)  { 
 
  //... 
 
}

@RequestMapping("/test")  
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {  
  
  //...  
  
}
@ResponseStatus(value=HttpStatus.FORBIDDEN, reason="出现了错误")
public class UserException extends RuntimeException{

    XXXXX
}

//当某处抛出UserException时,则会把value和reason返回给前端。
@RequestMapping("/testResponseStatus")
    public String testResponseStatus(int i){
        if(i==0)
            throw new UserNotMatchException();
        return "hello";
}
@ControllerAdvice  
public class GlobalExceptionHandler {  
    @ExceptionHandler(SQLException.class)   // 表示让Spring捕获到所有抛出的SQLException异常,并交由这个被注解的handleSQLException方法处理,
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR,reason=”sql查询错误”)  // @ResponseStatus指定了code和reason写到response上,返回给前端。
    @ResponseBody  
    public ExceptionResponse handleSQLException(HttpServletRequest request, Exception ex) {  
        String message = ex.getMessage();  
        return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);  
    } 
}

即表示让Spring捕获到所有抛出的SQLException异常,并交由这个被注解的handleSQLException方法处理,同时使用@ResponseStatus指定了code和reason写到response上,返回给前端。

SpringBoot注解

@Target(value=TYPE)  
 @Retention(value=RUNTIME)  
 @Documented  
 @Controller  
 @ResponseBody  
public @interface RestController

Bean扫描机制-概览

<beans ...> 
 <context:component-scan base-package="a.b" name-generator="a.SimpleNameGenerator"/> 
 </beans> 

Bean扫描机制-详解

javax.persistence下的注解

Lombok

Hibernate

jackson

上一篇下一篇

猜你喜欢

热点阅读