Spring注解开发

使用注解需要导入的依赖

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
     <!--开启注解支持-->
    <context:annotation-config/>

</beans>
  • @Autowired:自动装配(在实体类中可以不写set方法,前提是这个属性在IOC容器中存在,且Bean中得id与属性名一致)。
    它默认是通过ByType来实现自动装配。如果 Bean中得id不与属性名一致,一般要配合@Qualifier(value="XXX") Qualifier(预选) 注解一起使用
  public class person {
    //如果显式的定义了required为false,那么这个属性就可以为NULL,否则不可以
    @Autowired(required = false)
    @Qualifier(value = "dog1")
    private Dog dog;
    @Autowired
    @Qualifier(value = "cat1")
    private Cat cat;
    private String name;
  }
  • @Qualifier:通过将 @Qualifier 注解与我们想要使用的特定 Spring bean 的名称一起进行装配

  • @Resource:这是java自带的自动配置,功能比@Autowired强大。但项目开发上一般用@Autowired。
    @Resource默认是先通过ByName来实现自动装配,如果Name不一致再利用ByType去实现自动装配

  • @Component:component(组件)作用是将类托管到Spring中,使之成为Bean!用于pojo层(由于注解不能引用除自己之外的类,所以这个工作要给xml做)
    与之同样功能的衍生出来的注解

    • @Controller 用于controller层
    • @Repository 用于dao层
    • @Service 用于service层
      上面这四种注解的作用都一样,只是名字不同而已
  • @@Scope("singleton")//作用域的注解

  • @Value("Spring")//属性值注入的注解

  • @configuration//表示该类就相当于beans.xml配置文件(spring的配置文件)

  • @Bean//使用@Bean表示该方法交给spring接管(前提是该方法的类有 @configuration)@Bean的作用是,spring会自动将被@configuration注解的类进行对象化(也就是new 类),然后类中的方法被@Bean注解,就相当于在这个对象上加入了不同的方法

posted @ 2022-02-08 19:54  小罗要有出息  阅读(21)  评论(0编辑  收藏  举报