Spring基于注解的IOC学习总结

基于注解的IOC使用和基于XML方式的IOC的使用功能是一模一样的,只是注解方式是另一种使用方式而已,通过使用注解,可以完成相关的声明和配置。
先介绍一下XML和注解混合使用的情况,然后再改进为全注解的形式。


IOC的配置

首先,在pom.xml文件中,导入Spring IOC相关的约束和依赖。
例如:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day02_eesy_01anno_ioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>
</project>

其次,在resources文件夹下,建立bean.xml文件,导入相关约束和bean的配置,例如:

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
    context名称空间和约束中-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

相比于XML方式,我们只需要在beans标签内部,导入名为context:component-scan的标签,其中base-package属性指定Spring在哪个包下去扫描注解,找到我们定义的组件。

到此,我们已经配好了有关IOC注解的环境。

接下来介绍下如何应用注解实现IOC。

IOC注解的使用

类比于XML方式,注解可以按功能分为三类,即:

  • 用于创建对象的
  • 用于注入数据的
  • 用于改变作用范围的
  • 和生命周期相关的

用于创建对象的注解

@Component:

作用:用于把当前类对象存入spring容器中
属性:
	value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。

我们只需要在我们的类对象定义上,写入@Component注解,就将该类声明到了IOC容器当中,同时括号里对value属性赋值,即可指定bean的id。
例如:

@Component("accountService")
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao = null;
    
    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

类似如@Component注解,Spring又提供了三个类似的注解:

@Controller:一般用在表现层
@Service:一般用在业务层
@Repository:一般用在持久层

以上三个注解他们的作用和属性与Component是一模一样。
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰。

例如:

@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao = null;
    
    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

用于注入数据的注解

他们的作用就和在xml配置文件中的bean标签中写一个标签的作用是一样的。

@Autowired:

作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功。
如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
如果Ioc容器中有多个类型匹配时:
匹配变量名和bean的id一致的,若找不到与bean的id与该变量名一致,则匹配失败。
出现位置:
	可以是变量上,也可以是方法上
细节:
	在使用注解注入时,set方法就不是必须的了。

需要注意的是,当使用@Autowired注解自动注入时,如果Ioc容器中有多个类型匹配,Spring自动匹配变量名和bean的id一致的,若找不到与bean的id与该变量名一致,则匹配失败。
此时,我们可以通过**@Qualifier**注解,手动指定匹配容器中哪个id的bean。例如:

@Service("accountService")
public class AccountServiceImpl implements IAccountService {

@Autowired
@Qualifier("accountDao1")
private IAccountDao accountDao = null;

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

@Qualifier:

作用:在按照类中注入的基础之上再按照名称注入。
	 它在给类成员注入时不能单独使用,需要和@Autowired一同使用。但是在给方法参数注入时可以。
属性:
	value:用于指定注入bean的id。

@Resource:

作用:直接按照bean的id注入。它可以独立使用
属性:
	name:用于指定bean的id。

例如:


@Service("accountService")
public class AccountServiceImpl implements IAccountService {


    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;


    public void  saveAccount(){
        accountDao.saveAccount();
    }
}


以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
另外,集合类型的注入只能通过XML来实现。

@Value:

作用:用于注入基本类型和String类型的数据
属性:
	value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
		   SpEL的写法:${表达式}

@PropertySource:

作用:用于指定properties文件的位置
属性:
	value:指定文件的名称和路径。
关键字:classpath,表示类路径下

该注解的作用是,在我们使用@Value注解注入基本类型和String类型的数据时,我们注入的这些基本数据的值,是要存在一个后缀名为.properties的配置文件中。所以该注解,是指定存储数据的properties文件的位置。

例如:
我们在resources目录下创建一个名为jdbcConfig.properties的配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=1234

SpringConfiguration.java:

//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

	/**
	 * 用于创建一个 QueryRunner对象
	 */
	@Bean(name="runner")
	Public QueryRunner createQueryRunner(DataSource dataSource)
	{
		return new QueryRunner(dataSource);
	}
	
	/**
	 * 创建数据源对象
	 */
	
	@Bean(name="dataSource")
	public DataSource createDateSource(){
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.serDriverClass("com.mysql.jdbc.Driver");
		ds.serJdbcUrl("jdbc:mysql://localhost:3306/eesy");
		ds.serUser("root");
		ds.serPassword("1234");
		return ds;
	}
}

JdbcConfig.java文件中,需要注入jdbcConfig.properties文件中的数据:

public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

		//...... 省略
}

用于改变作用范围的注解

他们的作用就和在bean标签中使用scope属性实现的功能是一样的。

@Scope:

作用:用于指定bean的作用范围
属性:
	value:指定范围的取值。常用取值:singleton prototype

例如:

@Service("accountService")
@Scope("prototype")
public class AccountServiceImpl implements IAccountService {

	@Autowired
    private IAccountDao accountDao = null;

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

和生命周期相关的注解

他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的。

@PreDestroy:
作用:用于指定销毁方法
@PostConstruct:
作用:用于指定初始化方法

例如:

@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

    @PostConstruct
    public void  init(){
        System.out.println("初始化方法执行了");
    }

    @PreDestroy
    public void  destroy(){
        System.out.println("销毁方法执行了");
    }

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}


实现全注解形式

上面的例子,我们除了用到了注解形式,还是用到了XML配置文件,接下来,我们需要介绍更多的注解,实现全注解形式的IOC。

想要将XML配置文件取代,我们需要定义一个配置类。
我们在java目录下,创建一个config包,再创建一个名为SpringConfiguration.java的配置类。

@Configuration:

作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写,即该配置类为主配置类。

@ComponentScan:

作用:用于通过注解指定spring在创建容器时要扫描的包
 属性:
	 value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。

 我们使用此注解就等同于在xml中配置了:
     <context:component-scan base-package="com.itheima"></context:component-scan>

@Bean:

作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:
	name:用于指定bean的id。当不写时,默认值是当前方法的名称。
				指定name属性时,name关键词不能省略,因为参数中不止name一个参数。
细节:
	当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
 	查找的方式和Autowired注解的作用是一样的

前面我们讲到的**@Component是写在我们自定义类的上面,此时将该类加入到容器中。
而有时,我们需要非自定义的类作为bean对象注入到容器时,此时,我们就需要用到
@Bean**注解了。

例如,我们需要将xml里配置的这两个bean变成注解形式:

 <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

我们知道,注解形式我们定义的SpringConfiguration.java配置类文件,跟我们之前定义的XML配置文件是等价的,所以,要想将XML文件里的这两个bean转变成注解形式的,我们只需在我们的SpringConfiguration.java配置类中,注册这两个bean对象。

我们只需要定义一个函数,在该函数的返回值中,返回通过new创建的该类对象,并在该函数上面标注@Bean注解,例如:

@Configuration
@ComponentScan("com.itheima")
public class SpringConfiguration {

	/**
	 * 用于创建一个 QueryRunner对象
	 */
	@Bean(name="runner")
	Public QueryRunner createQueryRunner(DataSource dataSource)
	{
		return new QueryRunner(dataSource);
	}
	
	/**
	 * 创建数据源对象
	 */
	@Bean(name="dataSource")
	public DataSource createDateSource(){
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.serDriverClass("com.mysql.jdbc.Driver");
		ds.serJdbcUrl("jdbc:mysql://localhost:3306/eesy");
		ds.serUser("root");
		ds.serPassword("1234");
		return ds;
	}
}

@Import:

作用:用于导入其他的配置类
属性:
	value:用于指定其他配置类的字节码。
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

例如,我们再创建一个名为JdbcConfig.java的配置类,连接数据库相关的配置
此时,我们只需要在我们的主配置类文件上使用@Import导入该配置类。
例如:

@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
public class SpringConfiguration {

	/**
	 * 用于创建一个 QueryRunner对象
	 */
	@Bean(name="runner")
	Public QueryRunner createQueryRunner(DataSource dataSource)
	{
		return new QueryRunner(dataSource);
	}
	
	/**
	 * 创建数据源对象
	 */
	
	@Bean(name="dataSource")
	public DataSource createDateSource(){
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.serDriverClass("com.mysql.jdbc.Driver");
		ds.serJdbcUrl("jdbc:mysql://localhost:3306/eesy");
		ds.serUser("root");
		ds.serPassword("1234");
		return ds;
	}
}

到此为止,已经将实现全注解的相关注解全部介绍完了。

注解形式的IOC调用

注解形式的ApplicationContext接口的实现类,我们需要创建名为AnnotationConfigApplicationContext的实现类,然后通过getbean方法,获取指定id的bean对象,例如:

public class QueryRunnerTest {

    @Test
    public  void  testQueryRunner(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //获取queryRunner对象
        QueryRunner runner = ac.getBean("runner",QueryRunner.class);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章