Spring的一个核心功能是IOC,就是将Bean初始化加载到容器中,Bean可以使用Spring注解方式或者Spring XML配置方式加载到容器中。
一,组件类注解
@Component :标准一个普通的spring Bean类。
@Repository:标注一个DAO组件类。
@Service:标注一个业务逻辑组件类。
@Controller:标注一个控制器组件类。
注意:@Component可以代替@Repository,@Service,@Controller。因为这三个注解是被@Component标注的。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface test {
String value() default "";
}
1,当一个组件访问Dao层时可以使用@Repository进行注解
@Repository
public class DaoImpl implements Dao{
public void test(){
}
2,当一个组件代表业务层时,我们使用@Service进行注解
@Service(value="TestService")
//使用@Service注解不加value ,默认名称是Service
public class ServiceImpl implements Service {
@Autowired
private Dao dao;
}
3,当一个组件作为前端交互的控制层,使用@Controller进行注解
@Controller
public class Controller {
@Autowired
private Service service;
}
指定了某些类可作为Spring Bean类使用后,最好还需要让spring搜索指定路径,在Spring配置文件加入如下配置:
<context:component-scan base-package="org.springframework.*"/>
二:装配bean时常用的注解
1、注解介绍
@Autowired:属于Spring org.springframework.beans.factory.annotation包下,可用于为类的属性、构造器、方法进行注值
@Resource:不属于spring的注解
@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行
1,@Autowired
@Controller
public class Controller {
@Autowired //默认依赖的Dao 对象(Bean)必须存在
//@Autowired(required = false) 改变默认方式
@Qualifier("Service")
private Service service;
}
2,@Resource
public class AnotationTest {
@Resource(name = "myTest")
private Test test;
}
以上就是一些基本的spring注解。