[spring]spring注解开发

8.使用注解开发

1.bean

spring4以后,注解依赖于aop包,确保你的lib中有它

image-20220724105210839

确保开启了使用注解

<context:annotation-config/>

2.组件代替bean实现自动注入

在配置文件中自动扫描包下的所有类为bean

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

在类对象上加上注解@Component可以被扫描

  • @component (把普通pojo实例化到spring容器中,相当于配置文件中的
@Component

使用注解给属性注入值

package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author panglili
 * @create 2022-07-24-9:52
 */
@Component
public class People {
    private String name;
    @Value("123")
   public int age;
    private Dog dog;
    private Cat cat;
 }
}
  • 但是复杂的属性配置还是建议使用xml统一管理注入

3.component衍生的注解

dao:@repository

service:@service

controller:@controller

跟component功能相同只是能够使得分工更加的明确

小结:

xml与注解:

  • xml更加万能,适用于各种场合!维护简单方便
  • 注解 不是自己类使用不了,维护相对复杂

最佳实践:

  • xml用来管理bean
  • 注解只负责属性的注入
posted @ 2022-07-26 17:55  路漫漫qixiuyuanxi  阅读(33)  评论(0编辑  收藏  举报