Spring(二)Spring基于注解的IoC配置(最全注解)

点击【xml的IoC】可查看spring基于xml的IoC配置相关信息

一、基于注解的IoC配置

1.1 常用注解

1.2.1 用于创建对象
  • 其作用相当于:< bean id=" " class=" ">
  • @Component
    作用:
      可以使用此注解描述 Spring 中的 Bean,相当于在 xml 中配置一个bean,并且可以作用在任何层次。使用时只需将该注解标注在相应类上即可。
    属性:
      value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。
	@Component("accountDao")
	public class AccountDaoImpl implements IAccountDao {
	
	}
	//相当于在bean.xml配置了:
	<bean id="accountDao" 
	  	  class="com.wink.dao.impl.AccountDaoImpl">
	</bean>
  • @Controller
    一般作用在控制层,用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
  • @Service
    一般作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
  • @Repository
    一般作用在持久层(DAO层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
  • 上述的四个注解本质作用和属性都是一样的,在实际情况根据需求使用。如果注解中有且仅有一个属性要赋值时,并且名称是value,value在赋值是可以不写。
1.2.2 用于注入数据
  • 其作用相当于:< property name=" " ref=" “>< property name=” " value=" ">
  • @Autowired
    作用:
      自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他 bean 类型。当有多个 类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错。
    属性:
名称作用
byName根据 Property 的 name 自动装配,如果一个 Bean 的 name 和另一个 Bean 中的 Property 的 name 相同,则自动装配这个 Bean 到 Property 中。
byType根据 Property 的数据类型(Type)自动装配,如果一个 Bean 的数据类型兼容另一个 Bean 中 Property 的数据类型,则自动装配。
constructor根据构造方法的参数的数据类型,进行 byType 模式的自动装配。
autodetect如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。
no默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。
    @Autowired
    private QueryRunner runner;
    //相当于
    <property name="runner" ref="runner"></property>
  • @Resource
    作用:
      其作用与 Autowired 一样。其区别在于 @Autowired 默认按照 Bean 类型装配,而 @Resource 直接按照 Bean 的 id 注入。
    属性:
      name:指定 bean 的 实例名称。
        type:指定 bean 的 实例类型。
  • @Qualifier
    作用:
      在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowired 一起使用;但是给方法参数注入时,可以独立使用。
    属性:
       value:指定 bean 的 id。
  • @Value
    作用:
      注入基本数据类型和 String 类型数据的 。
    属性:
      value:用于指定值 。
1.2.3 用于改变作用范围
  • 其作用相当于:< bean id=" " class=" " scope=" ">

  • @Scope
    作用:
      指定 bean 的作用范围。
    属性:
      value:指定范围的值,取值:singleton prototype request session globalsession

  • 和生命周期相关的
    相当于:< bean id="" class=" " init-method=" " destroy-method=" " />
    @PostConstruct:用于指定初始化方法。
    @PreDestroy:用于指定销毁方法。

  • spring管理bean方式的比较:
    在这里插入图片描述

1.2.4 用于替换配置文件
  • @Configuration
    作用:
      用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。
    属性:
      value:用于指定配置类的字节码 。
@Configuration
public class SpringConfiguration {

}
  • @ComponentScan
    作用:
      用于指定 spring 在初始化容器时要扫描的包。相当于spring的xml配置文件中的:
    < context: component-scan base-package=“com.wink”/>
    属性:
      value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
  • @Bean
    作用:
      用于把当前方法的返回值作为bean对象存入spring的ioc容器中。
    属性:
      name:用于指定bean的id。当不写时,默认值是当前方法的名称 。
  • @Import
    作用:
      用于导入其他的配置类。
    属性:
      value:用于指定其他配置类的字节码。
      当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类。
  • @PropertySource
    作用:
      用于指定properties文件的位置。
    属性:
      value:指定文件的名称和路径。
      关键字:classpath,表示类路径下。
@Configuration
@ComponentScan(basePackage="com.wink")
@Import(JdbcConfig.class)
public class SpringConfiguration {

}
@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig{

}

1.2 基于纯注解的CRUD案例

在【Spring基于XML的IoC配置的CRUD案例】做更改

  1. 首先更改账户持久层和业务层,在类上添加创建对象和注入数据的注解,当使用注解注入属性时,set方法可以省略。
//AccountDaoImpl.java
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;
    
}
//AccountServiceImpl .java
@Service("accountService")
public class AccountServiceImpl implements IAccountService{
    @Autowired
    private IAccountDao accountDao;
    
}
  1. 创建spring连接数据库相关的配置类JdbcConfig.java,使用注解配置数据连接相关的信息,使用@Bean、@Value对数据源进行注入
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;

    //用于创建一个QueryRunner对象
    @Bean(name="runner")
    @Scope("prototype")//多例
    public QueryRunner createQueryRunner( @Qualifier("ds") DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    //创建数据源对象
    @Bean(name = "ds")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource cpds = new ComboPooledDataSource();
            cpds.setDriverClass(driver);
            cpds.setJdbcUrl(url);
            cpds.setUser(username);
            cpds.setPassword(password);
            return cpds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  1. 创建配置类SpringConfig.java(相当于bean.xml),使用@ComponentScan注入要扫描的包,使用@Import导入JdbcConfig字节码文件,最后使用@PropertySource注入数据库配置文件
@Configuration
@ComponentScan("com.wink")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfig {
}

二、Spring整合Junit

2.1 测试类中的问题和解决思路

在测试类中,每个测试方法都有以下两行代码:

ApplicationContext ac = new 
				ClassPathXmlApplicationContext("bean.xml");  
IAccountService as =
		ac.getBean("accountService",IAccountService.class); 

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。

2.2 配置步骤

  • @RunWith
      是一个运行器。使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的。
    @RunWith(JUnit4.class):指用JUnit4来运行
    @RunWith(SpringJUnit4ClassRunner.class):让测试运行于Spring测试环境
  • @ContextConfiguration
      告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置:
      locations:指定xml文件的位置,加上classpath关键字,表示在类路径下。
      classes:指定注解类所在地位置。
  • 导入junit必备的jar包
  • 使用@RunWith注解替换原有运行器
  • 使用@ContextConfiguration指定spring配置文件的位置
  • 使用@Autowired给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//或者@ContextConfiguration(locations= {"classpath:bean.xml"}) 
public class AccountServiceTest {

    @Autowired
    private IAccountService as = null;
    @Test
    public void testFindAll() {
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值