简单常用的注解
来源:互联网 发布:会员购淘宝u站 编辑:程序博客网 时间:2024/06/06 19:42
从Spring3.0开始,Spring javaConfig项目提供了很多的特性,包括使用java而不是xml定义bean,比如 :
@Configuration,@Bean,@Import,@DependsOn
@Component 是一个通用注解,可以用于任何的bean
——-@Repository通常用于注解Dao类,即持久层
——-@Service通常用于注解service层,即服务层
——-@Constorller通常用于Controller类,即控制层
在applicationCotext.xml中配置的bean默认都是单例模式,
那么在类上架注解的时候,可以设置其的作用域,设置为singleton就是单例模式。设置成protptype,每一次请求都会生成一个新的对象。
在测试的时候用applicationContext ,不要用XmlBeanFactory 去解析
//正确String [] location ={"applicationContext.xml"}; ApplicationContext ctx= new ClassPathXmlApplicationContext(location); TestService testService =(TestService) ctx.getBean("testServiceImpl"); testService.save("aaaaa");
//错误 ClassPathResource resource = new ClassPathResource( "applicationContext.xml"); BeanFactory bf = new XmlBeanFactory(resource); Concal concal =(Concal) bf.getBean("concal");
因为xmlBeanFactory默认不支持beanPostProcessor
用@Autowired注解的时候。可以加在三个地方
1、成员变量的上方(可以省略set、get方法)
2、set方法的上方
3、构造方法的上方(可以省略set、get )
**可以使用@Autowired来注解哪些中所周知的接口,eg:BeanFactory
,ApplicationContext,Environment,ResourceLoader,ApplicationEventPublisher,andMessageSource**
在使用@Autowired时候。当其加在list上时候,获得的是该list的泛型的对象
当其加在map上时,key是对象的首字母小写的名称,value是对象。
@Qualifier注解可以缩小范围,常用在 @Autowired适用的fields,constructors,multi-argument method这些允许参数级别的地方。可以使用@Qualifier来缩小范围
@Resource适用于成员变量、只有一个参数的setter方法,所以目标是构造器或者一个多参数的方法的时候,最好的使用方式是使用@Qualifier注解
@Bean
@Bean标识一个用于适配和初始化一个由SpringIoc容器管理的新对象的方法,类似于xml配置文件的
可以在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以)
上一点中。通常使用的是@Configuration
@Configurationpublic class appConfig{ @Bean public MyService myservice(){ return new MyService(); }}
这样的代码相当于在applicationContext.xml中的
<beans> <bean id="myService" class="com.yyy.services.MyserviceImpl"></beans>
都是返回一个对象
在@Bean中也可以这样使用
//这是指定这个方法的id@Bean(name="myFoo")public Foo foo(){ return new Foo();}//在初始化的时候,调用foo中的init方法@Bean(initMethod="init")public Foo foo(){ return new Foo();}//在销毁的时候,调用bar中的cleanup方法@Bean(destoryMethod="cleanup")public Bar bar(){ return new Bar();}
用@Bean注解默认的是单例的,想要不是单例模式,就要用@Scope来定义作用域
@Bean@Scope("prototype")public UserPreference userService(){ UserService service =new SimpleUserService(); service.set... return service;}
个人总结@Bean:
是加载在 @Configuration或者@Component 中的方法上。这个方法一般要返回一个实例对象 如new EXl();
- 简单常用的注解
- Spring boot简单常用的注解
- SpringMVC 常用注解,简单易懂
- springMVC常用注解简单解释
- LUA 一些常用函数的简单注解说明
- 常用注解的使用
- springmvc常用的注解
- JSF的常用注解
- junit的常用注解
- springmvc 常用的注解
- TestNG的常用注解
- webservice的常用注解
- Spring常用的注解
- Spring的常用注解
- Struts2的常用注解
- JMockit的常用注解
- 常用的注解
- SpringMVC的常用注解
- 手把手教程序员如何追到女神(附详细教程)
- TaskContinuationOptions items
- php5 mysqli 连数据库创建表
- AFHTTPRequestOperationManager简单使用
- OJ的runtime error exit code对应SIGTERM代码
- 简单常用的注解
- 类和对象
- linux自动编译的makefile
- RabbitMq应用在发送短信
- PHP cURL抓取华师学生个人课表
- Codeforces Round #325 (Div. 2) D. Phillip and Trains (BFS)
- C#的哈希
- 循环获取文件夹中子文件夹中的文件
- Leetcode101: Kth Smallest Element in a BST