您的位置:首页 > 编程语言 > Java开发

Spring 初探(十三)(Spring Boot annotation)

2017-01-06 17:28 162 查看
基于Spring Boot annotation 的总结性介绍

@RestController 
@Controller + @ResponseBody

@EnableAutoConfiguration
使得Spring根据所添加的依赖来决定配置的方式
以依赖中有spring-boot-starter-web(添加 Tomcat、 Spring MVC)为例  
假设开发web application 

当通过依赖的部分确定了所build的application的类型后 
其修饰了类(一般是位于包根目录的application类)就会自动搜索
所要使用的类(如build JPA时会搜索 @Entity修饰的类)

@ComponentScan
类似于原来Spring中的
<context:component-scan base-package="">
当没有base-package这个参数时 会从这个配置类
所位于的包开始找起 

其作用为 对于@Configuration修饰的Class 配置components 读取路径
与<context:component-scan> 平行生效

使用了这个配置后 会扫描指定路径下的类 如扫描到 @Component @Controller
@Service修饰的类 将其注册为bean(为之后通过@Autowired的自动依赖注入
创造方便)

这里最一般的是@Component 其仅仅表示类将作为依赖 被如ComponentScan
之类的进行读入 其它两个作为特殊的声明 Controller作为Web 相关
自不必说 Service : business service facade(外观)、

@Configuration
这个注解修饰的类 其由@Bean进行修饰的方法将会在一个Spring 容器中
用于动态生成一个bean对象。
@Cofiguration 包含了@Component
其一个简单示例如下:

Ex:

@Configuration
public class AppConfig {

@Bean
public MyBean myBean() {
// instantiate, configure and return bean ...
}
}
//调用的代码为:
 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 ctx.register(AppConfig.class);
 ctx.refresh();
 MyBean myBean = ctx.getBean(MyBean.class);
 // use myBean ...


要指出的是@Bean进行修饰的方法 在一般的文档例子中是使用无参数

的method 进行设定 但使用byType的方法进行设定的情况也是存在的

在我们使用的bookmarks例子中:
http://spring.io/guides/tutorials/bookmarks/
的Application中

及一个简单的示例:
http://www.tuicool.com/articles/nqUbyeA
使用AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext

初始化环境

一种对于上面使用AnnotationConfigApplicationContext 进行bean register替代方案

是Spring XML中beans环境中的配置:

Ex:

<beans>
<context:annotation-config/>
<bean class="com.acme.AppConfig"/>
</beans>


还有一种方法是使用 component scanning

由于@Configuration同时也是@Compoent 

可以指定 其它Class 通过@CompoentScan进行读取

@SpringBootApplication
@Configuration + @EnableAutoConfiguration + @CompnentScan 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息