Spring 温习笔记(二)Spring与注解

亦凉 2023-01-09 12:56 238阅读 0赞

数据源

考虑现实世界中的mobike 和ofo,他们就可以形象的比喻成为两种不同的”自行车源”,数据源实现的基本思想亦复如前,如c3p0,druid是当先最为流行的数据源。

spring与数据源

当在项目中使用数据源时,需要将控制数据源的权限交给spring,可通过spring来全面管理数据源。
在解耦设计思想的指导下,我们将Spring与数据源的配置文件和数据源自身的配置文件加以区分,小案例如下所示。
数据源配置文件:

  1. c3p0.driverDriver=com.mysql.jdbc.Driver
  2. c3p0.url=jdbc:mysql://192.168.168.128:7006/travel
  3. c3p0.user=root
  4. c3p0.password=root
  5. c3p0.initialSize=5
  6. c3p0.maxActive=10
  7. c3p0.maxWait=3000

Spring 配置文件
为了引入外部配置文件,需要在spring配置文件中引入context命名空间:
在这里插入图片描述
修改spring配置文件选择项

  1. <bean id="dataSourceC3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  2. <property name="driverClass" value="${c3p0.driverDriver}"></property>
  3. <property name="jdbcUrl" value="${c3p0.url}"></property>
  4. <property name="user" value="${c3p0.user}"></property>
  5. <property name="password" value="${c3p0.password}"></property>
  6. </bean>

根据模块化的设计思想,在总的配置文件中引入数据源配置文件

  1. <import resource="classpath:applicationContext_dataSource.xml"></import>

其测试例子如下所示:

  1. ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  2. ComboPooledDataSource dataSourceC3p0=(ComboPooledDataSource) appContext.getBean("dataSourceC3p0");
  3. System.out.println("XXXXXXXXX"+dataSourceC3p0);
  4. dataSourceC3p0.close();

成功获取到数据源
在这里插入图片描述

注解

然而很多时候单靠这些配置文件就使得整个项目的开发复杂度提升,在这情况下如何进行简化开发就成为各位猿首门迫切想要解决的问题,注解是大猿们在快速开发项目中必不可少的神器,注解的出现使得我们的开发再也不必面对反反复复的spring配置文件,给各位猿带来福音。下面就来温习一下spring注解开发。
spring的注解分为原始注解和新注解。

原始注解






















































注解 说明
@Component 使用在类上用于实例化Bean
@Controller 使用在web层类上用于实例化Bean
@Service 使用在service层类上用于实例化Bean
@Repository 使用在dao层类上用于实例化Bean
@Autowired 使用在字段上用于根据类型依赖注入
@Qualifier 结合@Autowired一起使用用于根据名称进行依赖注入
@Resource 相当于@Autowired+@Qualifier,按照名称进行注入
@Value 注入普通属性
@Scope 标注Bean的作用范围
@PostConstruct 使用在方法上标注该方法是Bean的初始化方法
@PreDestroy 使用在方法上标注该方法是Bean的销毁方法

notes: 使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。

  1. <!--注解的组件扫描-->
  2. <context:component-scan base-package="com.itheima"></context:component-scan>

@Component, @Repository, @Service,@Controller的区别

@Component是通用注解,其他三个注解是这个注解的拓展, 并且具有了特定的功能

  1. @Repository注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。
  2. @Controller层是spring-mvc的注解,具有将请求进行转发,重定向的功能。
  3. @Service层是业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。

@Autowired 与@Resource的区别

  1. @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
  2. @Autowired默认按类型装配(这个注解是属spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:

    @Autowired
    @Qualifier(“userDao”)
    //@Resource(name=”userDao”)
    private UserDao userDao;

在这种情况下我们就可以理解为@Autowired+@Qualifier=@Resource。

  1. @Resource(这个注解属于J2EE的),默认按照名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。例如:

    @Resource(name=”userDao”)
    private UserDao userDao;

@value

@Value(“#{}”) 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法。当然还有可以表示常量
@Value(“${xxxx}”)注解从配置文件读取值的用法
notes:如果采用了注解方法,那么可以省略setter和getter方法,如果使用的是xml配置方式,则需要写Setter和Getter方法。

新注解

使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:






























注解 说明
@Configuration 用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解
@ComponentScan 用于指定 Spring 在初始化容器时要扫描的包。 作用和在 Spring 的 xml 配置文件中的 <context:component-scan base-package=“com.itheima”/>一样
@Bean 使用在方法上,标注将该方法的返回值存储到 Spring 容器中
@PropertySource 用于加载.properties 文件中的配置
@Import 用于导入其他配置类

注解配置小案例

将所有的xml获取数据源的配置用注解代替
pom依赖坐标

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.1.10.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.12</version>
  11. <!--<scope>compile</scope>-->
  12. </dependency>
  13. <!--mysql驱动-->
  14. <dependency>
  15. <groupId>mysql</groupId>
  16. <artifactId>mysql-connector-java</artifactId>
  17. <version>5.1.26</version>
  18. <scope>compile</scope>
  19. </dependency>
  20. <!--druid连接池-->
  21. <dependency>
  22. <groupId>com.alibaba</groupId>
  23. <artifactId>druid</artifactId>
  24. <version>1.0.9</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.mchange</groupId>
  28. <artifactId>c3p0</artifactId>
  29. <version>0.9.5.2</version>
  30. </dependency>
  31. </dependencies>

service 层

  1. public interface UserService {
  2. public void save();
  3. }
  4. @Service("userService")
  5. public class UserServiceImpl implements UserService {
  6. private String username;
  7. private int age;
  8. private List<String> course;
  9. private Map<String, User> userMap;
  10. @Resource(name = "userDao")
  11. private UserDao userDao;
  12. private Properties properties;
  13. ...
  14. public void save() {
  15. System.out.println("my name is:"+username);
  16. System.out.println("my age is"+age);
  17. System.out.println("my course lists is :"+course);
  18. System.out.println("my favourite teachers is :"+userMap);
  19. System.out.println("my hobby is "+properties);
  20. userDao.save();
  21. }
  22. }

dao层

  1. public interface UserDao {
  2. public boolean save();
  3. }
  4. @Repository("userDao")
  5. public class UserDaoImpl implements UserDao {
  6. @PostConstruct
  7. public void initMethod(){
  8. System.out.println("初始化方法执行了......");
  9. }
  10. @PreDestroy
  11. public void destroyMethod(){
  12. System.out.println("销毁方法执行了.......");
  13. }
  14. public boolean save() {
  15. System.out.println("调用了save方法。。。。。");
  16. return false;
  17. }
  18. }

数据源配置

  1. //<context:property-placeholder location="classpath:c3p0.properties"/>
  2. @PropertySource("classpath:c3p0.properties")
  3. public class DataSourceConfiguration {
  4. @Value("${c3p0.driverDriver}")
  5. private String driver;
  6. @Value("${c3p0.url}")
  7. private String url;
  8. @Value("${c3p0.user}")
  9. private String user;
  10. @Value("${c3p0.password}")
  11. private String password;
  12. @Bean("dataSource")
  13. public DataSource getDataSource() throws PropertyVetoException {
  14. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  15. dataSource.setDriverClass(driver);
  16. dataSource.setJdbcUrl(url);
  17. dataSource.setUser(user);
  18. dataSource.setPassword(password);
  19. return dataSource;
  20. }
  21. }

spring 注解文件配置

  1. @Configuration
  2. //<context:component-scan base-package="com.feitian"/>
  3. @ComponentScan("com.feitian")
  4. //<import resource="applicationContext_*.xml"/>在中括号中可以加入多个class
  5. @Import({ DataSourceConfiguration.class})
  6. public class SpringConfiguration {
  7. }

注解测试

  1. public class Anno {
  2. @Test
  3. public void test01(){
  4. ApplicationContext applicationContext= new AnnotationConfigApplicationContext(SpringConfiguration.class);
  5. UserService userService = (UserService) applicationContext.getBean("userService");
  6. userService.save();
  7. }
  8. }

spring 集成junit

spring 集成注解配置文件

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. //@ContextConfiguration("classpath:applicationContext.xml")
  3. @ContextConfiguration(classes = { SpringConfiguration.class})
  4. public class SpringJunitTest {
  5. @Autowired
  6. private UserService userService;
  7. @Test
  8. public void test01(){
  9. userService.save();
  10. }
  11. }

当spring 需要集成xml配置文件时,将ContextConfiguration替换即可

  1. @ContextConfiguration("classpath:applicationContext.xml")

发表评论

表情:
评论列表 (有 0 条评论,238人围观)

还没有评论,来说两句吧...

相关阅读