springIOC注解的使用

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_29150765/article/details/85157034
  • 导入context名称控件约束
  • 说明创建容器时要扫描的包
  • 添加注解
  • 使用el表达式,读取properties
<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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--说明创建容器时扫描的包-->
    <context:component-scan base-package="spring"></context:component-scan>
    <!--指定properties文件位置-->
    <context:property-placeholder location="spring-properties.properties" />
</beans>

在需要new的对像的类上添加注解,将对象放入spring容器中

@Component(value = "accountService")
public class AccountServiecImp implements IAccountService {
}

读取的方式仍然相同

public class Client {
    public static void main(String[] args){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-bean.xml");
        IAccountService accountService = ac.getBean("accountService",IAccountService.class);
        System.out.println(accountService);
    }
}

注解分类

用于创建对象

@Component:相当于spring的xml文件当中写bean标签;它的value属性指定bean的id;不写时对象名称默认为类名首字母小写。
由它衍射的还有Controller(表现层)、Service(业务层)、Repsitory(持久层);它们继承Component使用相同的方法;区别在于提供更明确的语义化来指定不同层的对象。
若属性只是用value,则可省略只写名称

用于注入数据

注入数据的作用就是为对象的属性赋值;不然属性只是声明了变量/对象类型没有具体值。

  1. @Autowired:自动按照类型注入,只要bean容器中有唯一类型匹配(bean对象的类型和声明的对象类型匹配),则直接注入成功;若有多种对象类型匹配(实现相同接口),则按照变量名称和bean中对象id匹配;该注解可以省略set方法
    其属性require="true/false"标识是否必须注入成功,报错内容不同而已;写不写没啥大影响,默认有该属性并且为true。
  2. @Qualifier(value = "beanId")Autowired下使用,指定bean对象id;不能单独使用
  3. @Resource(name = "beanId")
    以上三种只能用来注入bean对象类型,不能注入基础数据类型或集合。
  4. @Value:用于注入基本类型和String类型;其属性为value指定要注入的数据,并支持spring的el表达式:${表达式}

用于改变作用范围

@Scope:值:默认singletonprototype和xml文件中的该属性相同

和生命周期相关

  1. @PostContruct:用于指定初始化方法,和配置文件中的init-method属性是一样的
  2. @PreDestroy:用于指定销毁方法,和配置文件中的destroy-method属性一样

配置类,代替XML

直接读取配置注解类

ApplicationContext ac = 
          new AnnotationConfigApplicationContext(SpringConfiguration.class);
  1. Configuration:表明当前类是spring的配置类;如果只是写到AnnotationConfigApplicationContext构造函数中的字节码,则可以省略;如果没有写到构造函数中,但是在加载要扫描的包时,需要读到此配置,则必须写。
  2. Bean(name="objectName"):把当前方法的返回值存入spring的容器中;属性name用于指定bean的id,默认为当前方法名称。
  3. Qualifier:Spring框架给带有bean注解的方法创建创建对象时,如果方法有参数,会用方法参数的数据类型前往容器中查找;如果有唯一的一个类型匹配,则直接给方法的参数注入。如果找到多个,则使用该注解,该注解也可以独立使用。
  4. ComponentScan(name="backageName"):用于指定spring要扫描的包。
  5. Import(value="Class<?>[]"):用于导入其他的配置类
  6. PropertySource("xxx.properties"):读取properties配置文件,结合el表达式使用

猜你喜欢

转载自blog.csdn.net/qq_29150765/article/details/85157034