Spring

spring之常用注解

2018-07-12  本文已影响7人  Sophie12138

1、@Component

管理组件的通用形式,写在类名之上,将对象注入ApplicationContext容器中。

2、@Controller

对应mvc模式的c,也即为控制层,代码形式如下:

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

使用@Controller注解标识UserController之后,就表示要把UserController交给Spring容器管理,在Spring容器中会存在一个名字为"UserController"的组件,这个名字是根据UserController类名来取的。注意:如果@Controller不指定其value,则默认的bean名字为这个类的类名首字母小写,如果指定value【@Controller(value="UserController")】或者【@Controller("UserController")】,则使用value作为bean的名字。
这里的UserController还使用了@Scope注解,@Scope("prototype")表示将UserController的范围声明为原型,可以利用容器的scope="prototype"来保证每一个请求有一个单独的UserController来处理,避免线程安全问题。spring 默认scope 是单例模式(scope="singleton"),这样只会创建一个Action对象,每次访问都是同一Action对象,数据不安全,scope="prototype" 可以保证当有请求的时候都创建一个UserController对象。

3、@Service

1 @Service("userService")
2 public class UserServiceImpl implements UserService {
3 ………
4 }

注入后使用接口类型访问,更为安全可靠。

1 // 注入userService
2 @Resource(name = "userService")
3 private UserService userService;

4、@Repository

@Repository对应数据访问层Bean ,例如:

1 @Repository(value="userDao")
2 public class UserDaoImpl extends BaseDaoImpl<User> {
3 ………
4 }

5、@Autowired

推荐尽量使用@Autowired进行组件的注入

上一篇 下一篇

猜你喜欢

热点阅读