04-Spring的注解开发

配置注解扫描

对于DI使用注解,将不再需要在Spring配置文件中声明部bean实例。Spring中使用注解,需要在原有Spring运行环境基础上在做一些改变,完成以下三个步骤:
(1)导入AOP的JAR包。因为注解的后台实现用到了AOP编程。

  • spring-aop-4.2.1.RELEASE.jar
    (2)需要更换配置文件头,即添加相应的约束:【context约束】
  • 约束在%spring_home%\docs\spring-framework-reference\html\xsd-configuration.html文件中。
    (3)需要在Spring配置文件中配置组件扫描器,用于在指定的基本包中扫描注解。

1. 常见注解

  1. @Component:定义Bean,需要在类上使用@Component,该注解的value属性用于指定该Bean的id值。
// 该注解参数省略了value属性,该属性用于指定Bena的id
@Component("myStudent")
public class Student{
    private String name;
    private int age;
}

另外:Spring还提供了3个功能基本和@Component等效的注解:
@Reposity:用于对DAO实现类进行注解
@Service:用于对Service实现类进行注解
@Controller:用于对Controller实现类进行注解
之所以创建这三个功能与@Component等效的注解,是为了以后对其进行功能上的扩展,是他们不再等效。

  1. @Scope:Bean的作用域,需要在类上使用注解@Scope,其value属性用于指定作用域,默认为singleton。
@Scope("prototype")
@Component("UserService")
public class UserServiceImpl implements IUserService{
    public void doSome(){
        System.out.println("执行doSome()……");
    }
}
  1. @Value:基本类型属性输入。需要在属性上使用注解@Value,该注解的value属性用于指定要注入的值。使用该注解完成属性注入时,类中无需setter。当然,若属性有setter,则也可将其加到setter上。
@Component("myStudent")
public class Student{
    @Value("张三")
    private String name;
    @Value(23);
    private int age;
    @Override
    public String toString(){
        return "Student [ name="+name+",age"+age+"]";
    }
}
  1. @Autowired:按类型注入域属性
    需要在域属性上使用注解@Autowired,该注解默认使用按类型自动装配Bean的方式。使用该注解完成属性注入时,类中无需setter。当然,若属性有setter,则也可将其加到setter上。

猜你喜欢

转载自www.cnblogs.com/zhy0720/p/10453674.html