【spring】 基于注解的IOC配置

spring基于注解的IOC配置

常用注解

  1. 创建对象

相当于XML的 <bean id="" class="">

  • @Component

作用 : 把资源让 spring 来管理。相当于在 xml 中配置一个 bean。

属性 :value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

  • 衍生注解

@Controller: 一般用于表现层的注解。

@Service: 一般用于业务层的注解。

@Repository: 一般用于持久层的注解。

  1. 注入数据
  • @Autowired

作用:自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个 类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到 就报错。

  • @Qualifier

作用 : 在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire 一起使用;但是给方法参数注入时,可以独立使用。

属性 : value : 指定 bean 的 id。

  • @Resource

作用 : 直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
属性 : name:指定 bean 的 id。

  • @Value

作用: 注入基本数据类型和 String 类型数据的

属性: value:用于指定值

  1. 改变作用范围

<bean id="" class="" scope="">

  • @Scope

属性: value:指定范围的值。

取值 : singleton(单例,默认), prototype(多例), request, session, globalsession

  1. 生每周期

<bean id="" class="" init-method="" destroy-method="" />

  • @PostConstruct, @PreDestroy

作用:指定初始化和销毁方法

纯注解配置

  1. @Configuration

作用 : 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)。

属性: value:用于指定配置类的字节码

  1. @ComponentScan

作用: 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:<context:component-scan base-package=“com.itheima”/>是一样的。

属性: basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。

  1. @Bean

作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
属性: name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。

  1. @PropertySource

作用:用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到 properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
属性: value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

  1. @Import

作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。
属性: value[]:用于指定其他配置类的字节码。

  1. 通过注解获取容器

    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    

SpringConfig 配置类

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

}

JdbcConfig 连接数据库配置累

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对象
     * @param dataSource
     */
    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    /**
     * 创建数据源对象
     */
    @Bean(name="ds2")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

AccountDaoImpl 账户的持久层实现类

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

AccountServiceImpl 账户的业务层实现类

Service("accountService")
public class AccountServiceImpl implements IAccountService{
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
}
发布了18 篇原创文章 · 获赞 0 · 访问量 271

猜你喜欢

转载自blog.csdn.net/shijyuan/article/details/104862893