当前位置: 首页 > news >正文

Spring_day2

基于注解的 IOC 配置

  1. 使用@Component 注解配置管理的资源
/**
* 账户的业务层实现类
*/
@Component("accountService")
public class AccountServiceImpl implements IAccountService {private IAccountDao accountDao;public void setAccountDao(IAccountDao accountDao) {this.accountDao = accountDao;
}
}
/**
* 账户的持久层实现类
*/
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {private DBAssit dbAssit;
}
  • 注意:
    当我们使用注解注入时,set 方法不用写

  1. 创建 spring 的 xml 配置文件并开启对注解的支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 告知 spring 创建容器时要扫描的包 -->
<context:component-scan base-package="cn.myp666"></context:component-scan><!-- 配置 dbAssit -->
<bean id="dbAssit" class="cn.myp666.dbassit.DBAssit"><property name="dataSource" ref="dataSource"></property>
</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:///spring_day02"></property><property name="user" value="root"></property><property name="password" value="1234"></property>
</bean></beans>



常用注解

用于创建对象的

  • 相当于:<bean id="" class="">
  1. @Component
  • 作用:
    • 把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
  • 属性:
    • value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

  1. @Controller,@Service,@Repository
  • 他们三个注解都是针对第一个的衍生注解,他们的作用及属性都是一模一样的。
    他们只不过是提供了更加明确的语义化。

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

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

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

用于注入数据的

  • 相当于:
    <property name="" ref="">

    <property name="" value="">

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

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

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

  1. @Value
  • 作用:
    • 注入基本数据类型和 String 类型数据的
  • 属性:
    • value:用于指定值

用于改变作用范围的:

  • 相当于:<bean id="" class="" scope="">
  1. @Scope
  • 作用:
    • 指定 bean 的作用范围。
  • 属性:
    • value:指定范围的值。

      • 取值:singleton prototype request session globalsession

和生命周期相关的:(了解)

  • 相当于:<bean id="" class="" init-method="" destroy-method="" />
  1. @PostConstruct
  • 作用:
    用于指定初始化方法。

  1. @PreDestroy
  • 作用:
    用于指定销毁方法。


使用纯注解配置—新注解说明

  1. @Configuration
  • 作用:
    • 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)。
  • 属性:
    • value:用于指定配置类的字节码
  • 示例代码:
/**
* spring 的配置类,相当于 bean.xml 文件
*/
@Configuration
public class SpringConfiguration {
}
  • 注意:
    我们已经把配置文件用类来代替了,但是如何配置创建容器时要扫描的包呢?
    请看下一个注解。

  1. @ComponentScan
  • 作用:

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

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

/**
* spring 的配置类,相当于 bean.xml 文件
*/
@Configuration
@ComponentScan("cn.myp666")
public class SpringConfiguration {
}
  • 注意:
    我们已经配置好了要扫描的包,但是数据源和 JdbcTemplate 对象如何从配置文件中移除呢?
    请看下一个注解。

  1. @Bean
  • 作用:
    • 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
  • 属性:
    • name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。
  • 示例代码:
/**
* 连接数据库的配置类
*/
public class JdbcConfig {
/**
* 创建一个数据源,并存入 spring 容器中
* @return
*/
@Bean(name="dataSource")
public DataSource createDataSource() {try {ComboPooledDataSource ds = new ComboPooledDataSource();ds.setUser("root");ds.setPassword("1234");ds.setDriverClass("com.mysql.jdbc.Driver");ds.setJdbcUrl("jdbc:mysql:///spring_day02");return ds;} catch (Exception e) {throw new RuntimeException(e);}
}
/**
* 创建一个 DBAssit,并且也存入 spring 容器中
* @param dataSource
* @return
*/
@Bean(name="dbAssit")
public DBAssit createDBAssit(DataSource dataSource) {return new DBAssit(dataSource);}
}
  • 注意:
    我们已经把数据源和 DBAssit 从配置文件中移除了,此时可以删除 bean.xml 了。
    但是由于没有了配置文件,创建数据源的配置又都写死在类中了。如何把它们配置出来呢?
    请看下一个注解。

  1. @PropertySource
  • 作用:

    • 用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
  • 属性:

    • value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:
  • 示例代码:

/**
* 连接数据库的配置类
*/
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;
/**
* 创建一个数据源,并存入 spring 容器中
* @return
*/
@Bean(name="dataSource")
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);}
}}
  • 注意:
    此时我们已经有了两个配置类,但是他们还没有关系。如何建立他们的关系呢?
    请看下一个注解。

  1. @Import
  • 作用:
    • 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。
  • 属性:
    • value[]:用于指定其他配置类的字节码。
  • 示例代码:
@Configuration
@ComponentScan(basePackages = "cn.myp666.spring")
@Import({ JdbcConfig.class})
public class SpringConfiguration {
}
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig{
}
  • 注意:
    我们已经把要配置的都配置好了,但是新的问题产生了,由于没有配置文件了,如何获取容器呢?
    请看下一小节。

  1. 通过注解获取容器:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);



Spring 整合 Junit

  • 问题
    在测试类中,每个测试方法都有以下两行代码:
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);

       这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

  1. 第一步:拷贝整合 junit 的必备 jar 包到 lib 目录
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version>
</dependency>
  1. 第二步:使用@RunWith 注解替换原有运行器
/**
* 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
  1. 第三步:使用@ContextConfiguration 指定 spring 配置文件的位置
/**
* 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:bean.xml"})
public class AccountServiceTest {
}
  • @ContextConfiguration 注解:
    • locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
    • classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
  1. 第四步:使用@Autowired 给测试类中的变量注入数据
/**
* 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {@Autowiredprivate IAccountService as ;
}

http://www.taodudu.cc/news/show-1476402.html

相关文章:

  • 网络 | 应用层-websocket协议报文格式解析
  • 精酿啤酒:精酿文化的传承者与创新者
  • 2024年将改变人类生活的七大技术
  • 计算机类的英语
  • 单播、组播、广播
  • AI图像生成-基本步骤
  • Spring_day3
  • Spring_day4
  • SpringMVC_day1
  • SpringMVC_day1_常用注解
  • SpringMVC_02
  • Error creating bean with name 'dataSource' defined in class path resource [spring/spring-dao.xml]:
  • SpringSecurity入门
  • 服务注册不进eureka
  • Spring Cloud总结
  • 在此之前的博客地址
  • golang利用反射写入excel的简单工具类
  • 实习工作难点记录
  • c 结构体之位域(位段)
  • 辗转相除求最大公约数,最大公倍数
  • Ubuntu“无法解析或打开软件包的列表或是状态文件”的解决办法。
  • 错误:cc1: error: unrecognized command line option “-m32”
  • 在编写mini2440 helloworld驱动遇到的问题
  • [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
  • [leetcode] Reverse Integer 反转一个整数
  • [leetcode] Palindrome Number 回文数判断
  • [leetcode] Longest Common Prefix 字符窜最长公共前缀判断
  • [leetcode] Single Number 查找数组中的单数
  • [leetcode] Power of Two 判断一个数是否是2的平方
  • [leetcode] Max Points on a Line 判断最多有多少个点在同一条直线上
  • 使用selenium webdriver进行元素定位
  • 一个动态增长的栈实现
  • sublime cscope使用方法
  • [leetcode] 24. Swap Nodes in Pairs
  • sublime text常用快捷键整理
  • kmp算法字符串匹配C语言实现