spring的常用注解

利用注解可以简化spring对bean的操作,使用起来也很容易

常用Spring注解@Component、@Repository、@Service、@Controller

@Repository、@Service、@Controller是@Component的子注解,基本上没多大区别,现在更多的是提示开发人员注解的类不同

从字面就可以看出@Repository标志持久化类,@Service标志业务类dao层,@Controller标志控制类action


<?xml version="1.0" encoding="UTF-8" ?>   
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">   
     
    <context:component-scan base-package="com.mytest">     
</beans>  
在spring配置文件中写入该标签后,spring容器就会自动在com.mytest包下搜索添加了上诉四个标记的类,并把他们注入成bean

getBean的默认名称是类名小写,如果想要自定义可以@Service("Myname")这样

要使用自动扫描需要加上xmlns:context="http://www.springframework.org/schema/context"命名空间

 http://www.springframework.org/schema/context  
  http://www.springframework.org/schema/context/spring-context-2.5.xsd和这两个url




@Component
public class Card {
	private int id;
	private String code;
	@PostConstruct
	public void init(){
		id=1;
		code="null";
}
@PostConstruct可以指定注入bean的初始化方法,@PreDestroy指定销毁方法



@Componet
public class User {
	private int id;
	private String username;
	private String password;
	@Autowired
	private Card card;
...........................................
}
@Autowired可以标志为User注入的类


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值