SpringBoot常用注解

@SpringBootApplication :

用在引導(dǎo)類上

  • @SpringBootConfiguration:聲明當(dāng)前類是SpringBoot應(yīng)用的配置類,項目中只能有一個。所以一般我們無需自己添加。
  • @EnableAutoConfiguration:開啟spring應(yīng)用程序的自動配置,SpringBoot基于你所添加的依賴和你自己定義的bean,試圖去猜測并配置你想要的配置。比如我們引入了spring-boot-starter-web,而這個啟動器中幫我們添加了tomcat、SpringMVC的依賴。此時自動配置就知道你是要開發(fā)一個web應(yīng)用,所以就幫你完成了web及SpringMVC的默認(rèn)配置了!這個自動配置可以在依賴spring-boot-autoconfigure中查看
  • @ComponentScan:開啟注解掃描,如果沒有指定這些屬性,那么將從聲明這個注解的類所在的包開始,掃描包及子包。被@controller@service、@repository@component、@Configuration注解的類,都會把這些類納入進(jìn)spring容器中進(jìn)行管理,可以無需使用@Bean。
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

@RestController

在XxxxController類使用,相當(dāng)于@ResponseBody@Controller聯(lián)用
在什么情況下使用@ResponseBody 注解?

@RestController
public class HelloController {

    @GetMapping("show")
    public String test(){
        return "hello Spring Boot!";
    }
}

@service

用于事務(wù)

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id){
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public void deleteById(Long id){
        this.userMapper.deleteByPrimaryKey(id);
    }
}

@repository

持久層

@component

泛指組件,當(dāng)組件不好歸類的時候,我們可以使用這個注解進(jìn)行標(biāo)注。

//攔截器
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle method is running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion method is running!");
    }
}

java配置

@Configuration:聲明一個類作為配置類,然后Spring容器會根據(jù)它來生成IoC容器去配置Bean。用于XxxxConfiguration類中。
@PropertySource:指定外部屬性文件。@PropertySource("classpath:jdbc.properties")
@Value:屬性注入
@Bean:聲明在方法上,將方法的返回值加入Bean容器,Spring會自動調(diào)用該方法,將方法的返回值加入Spring容器中。如果沒有帶參數(shù),則會以函數(shù)名(如例子中的dataSource)作為Bean的名稱保存,也可以對name屬性進(jìn)行賦值,主動配置名字。
@Autowired:在任意位置從Spring容器中提取并注入到屬性當(dāng)中

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfiguration {

    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

測試

@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @GetMapping("show")
    public String test(){
        return "hello Spring Boot!";
    }
}

Spring其他裝配Bean的方法

除了@Bean外,Spring還允許掃描裝配Bean到IoC容器中。
@Component:標(biāo)明哪個類被掃描進(jìn)入Spring IoC容器中。
@ComponentScan:標(biāo)明采用何種策略去掃描裝配Bean。一般直接用@SpringBootApplication代替

SpringBoot的屬性注入方式

@ConfigurationProperties(prefix = "jdbc")
SpringBoot的屬性注入方式,支持各種java基本數(shù)據(jù)類型及復(fù)雜類型的注入。要求修飾的類里面的命名與配置一致,且必須有set方法,從而可以省去@Value

@EnableConfigurationProperties(JdbcProperties.class)
在其他類注入@ConfigurationProperties配置過的類時,需要添加該注解。

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    // ... 略
    // getters 和 setters
}

注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    @Autowired
    private JdbcProperties jdbcProperties;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }

}

@RequestMapping

配置 Web 請求的映射,用{}來表明它的變量部分

    @RequestMapping(value = {  
        "",  
        "/page",  
        "page*",  
        "view/*,**/msg"  
    })

@GetMapping

@GetMapping是一個組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫。

@PostMapping

@PostMapping是一個組合注解,是@RequestMapping(method = RequestMethod.POST)的縮寫。

@PathVariable

@RestController
@RequestMapping("test")
public class MyController {

    @Autowired
    private User user;

    @GetMapping("{subPath}")
    public String test(@PathVariable("subPath") String subPath) {
        if (subPath.equals("all")) {
            return user.toString();
        } else if (subPath.equals("name")) {
            return user.getUserName();
        } else {
            return null;
        }
    }
}
@RequestMapping("/user/{username}/blog/{blogId}")
@ResponseBody
public String getUerBlog(@PathVariable String username , @PathVariable int blogId) {
    return "user: " + username + "blog->" + blogId;
}

這種情況下,Spring能夠根據(jù)名字自動賦值對應(yīng)的函數(shù)參數(shù)值,也可以在@PathVariable中顯示地表明具體的URL變量值。
在默認(rèn)情況下,@PathVariable注解的參數(shù)可以是一些基本的簡單類型:int,long,Date,String等,Spring能根據(jù)URL變量的具體值以及函數(shù)參數(shù)的類型來進(jìn)行自動轉(zhuǎn)換,例如/user/fpc/blog/1,會將“fpc”的值賦給username,而1賦值給int變量blogId。

@RequestParam

@RestController
@RequestMapping("/test")
public class Test {

    @GetMapping("test.do")
    // 指定將username參數(shù)的值傳遞到該方法的name參數(shù)上
    public void test(@RequestParam(name = "username") String name) {
        System.out.println(name);
    }

    @GetMapping("user.do")
    // 指定將username參數(shù)的值傳遞到該方法的user參數(shù)上,alias參數(shù)的值則傳遞到該方法的a參數(shù)上
    public void userAndAlias(@RequestParam(name = "username")String user, @RequestParam(name = "alias")String a) {
        System.out.println(user);
        System.out.println(a);
    }
}

@RequestMapping與@RequestParam注解

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容