Spring常用注解简述

使用注解构造IOC、替代传统的applicationContext.xml配置<bean/>和<property/>

传统的spring要在applicationContext.xml中配置:①<bean>类   ②<property>属性   如果有100个类和若干个属性,那么我们就要写成百上千个<bean>、<property>,这种就不利于维护,使用注解就能够解决这个问题。(项目中的方法也可以使用注解来替代)

在使用类注解前要在applicationContext.xml文件中添加:

<context:component-scan base-package="news"></context:component-scan>

注意:base-package可以指定一个包也可指定多个包,多个包逗号隔开

使用了<context:component-scan/>之后就可以把<context:annotation-config/>移除,因为<context:component-scan/>也能实现扫描包路径。

1.(类)@Controller

@Controller是对应控制层的<bean>,也就是action类

用法:

1 @Controller
2 @Scope("prototype")
3 public class NewsAction extends ActionSupport{
4 ……
5 }

注意:如果@Controller不指定其value【@Controller】,则默认的bean名字为这个类的类名首字母小写,如果指定value【@Controller(value="UserAction")】或者【@Controller("UserAction")】,则使用value作为bean的名字。

2、(类)@ Service

@Service对应的是业务层Bean

用法:

1 @Service("NewsService")
2 public class NewsServiceImpl implements NewsService {
3 ………
4 }

3、(类)@ Repository

@Repository对应数据访问层Bean,部分技术人员也喜欢叫dao类

用法

1 @Repository(value="NewsDao")
2 public class NewsDaoImpl extends NewsDaoImpl {
3 ………
4 }

注意:以上三种(@Controller、@Service、@Repository)是针对不同层的类所使用的注解,下面的是针对属性所使用的注解:

4.(属性)@ Autowired (不推荐使用,建议使用@Resource)

@Qualifier("...")

用法(在实现类中封装一个属性并私有化,在属性上面添加@Autowired @Qualifier)

如下:

public class NewsDaoImpl implements NewsDao {
   //这种方式是spring注解
   @Autowired
@Qualifier("mySessionFactory")
private SessionFactory sf;
}

 注意:加入@Qualifier是为了让spring准确地知道要注入的对象,括号里自定义属性名字

5.(属性)@Resource(jdk)

用法:

public class NewsDaoImpl implements NewsDao {
    @Resource(name="mySessionFactory")
    private SessionFactory sf;
}

通过@Resource注解来给属性sf注入一个名字为mySessionFactory的值

Spring 的详细介绍请点这里
Spring 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-11/137195.htm