Spring--注解--杂记--待更新

  1. @Configuration有什么用?
  2. @Configuration和XML有什么区别?哪种好?
  3. Spring是如何基于来获取Bean的定义的?
  4. @Autowired 、 @Inject、@Resource 之间有什么区别?
  5. @Value、@PropertySource 和 @Configuration?
  6. Spring如何处理带@Configuration @Import的类?
  7. @Profile有什么用?
  8. @Configuration 如何嵌套?
  9. Spring如何对Bean进行延迟初始化?
  10. Spring项目怎么进行单元测试?
  11. @Configuration 使用上有哪些约束?

@Configuration 基本说明

定义:指示一个类声明一个或者多个@Bean 声明的方法并且由Spring容器统一管理,以便在运行时为这些bean生成bean的定义和服务请求的类。例如:

@Configuration
public class AppConfig {

  @Bean
  public MyBean myBean(){
    return new MyBean();
  }
}

上述AppConfig 加入@Configuration 注解,表明这就是一个配置类。有一个myBean()的方法,返回一个MyBean()的实例,并用@Bean 进行注释,表明这个方法是需要被Spring进行管理的bean。@Bean 如果不指定名称的话,默认使用myBean名称,也就是小写的名称。

通过注解启动

通过启动一个AnnotationConfigApplicationContext 来引导这个@Configuration 注解的类,比如:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();

在web项目中,也可以使用AnnotationContextWebApplicationContext或者其他变体来启动。

新建一个SpringBoot项目

pom.xml 文件如下

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.spring.configuration</groupId>
    <artifactId>spring-configuration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-configuration</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在config 包下新建一个MyConfiguration环境配置,和上面的示例代码相似,完整的代码如下:

@Configuration
public class MyConfiguration {

    @Bean
    public MyBean myBean(){
        System.out.println("myBean Initialized");
        return new MyBean();
    }
}

说明MyConfiguration 是一个配置类,能够在此类下面声明管理多个Bean,我们声明了一个MyBean的bean,希望它被容器加载和管理。

在pojo包下新建一个MyBean的类,具体代码如下

public class MyBean {

    public MyBean(){
        System.out.println("generate MyBean Instance");
    }

    public void init(){
        System.out.println("MyBean Resources Initialized");
    }
}

新建一个SpringConfigurationApplication类,用来测试MyConfiguration类,具体代码如下

public class SpringConfigurationApplication {
    public static void main(String[] args) {
//        AnnotationConfigApplicationContext context = = new AnnotationConfigApplicationContext(MyConfiguration.class)
          // 因为我们加载的@Configuration 是基于注解形式的,所以需要创建AnnotationConfigApplicationContext
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册MyConfiguration 类并刷新bean 容器。
        context.register(MyConfiguration.class);
        context.refresh();
    }
}

输出:

myBean Initialized
generate MyBean Instance

从输出的结果可以看到,默认名称为myBean 的bean随着容器的加载而加载,因为myBean方法返回一个myBean的构造方法,所以myBean被初始化了。

通过XML 的方式来启动

可以通过使用XML方式定义的开启基于注解的启动,然后再定义一个MyConfiguration的bean,在/resources 目录下新建 application-context.xml 代码如下:

<?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"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>

    <!-- 相当于基于注解的启动类 AnnotationConfigApplicationContext-->
    <context:annotation-config />

    <bean class="com.spring.configuration.config.MyConfiguration"/>

</beans>

需要引入applicationContext.xml ,在SpringConfigurationApplication 需要进行引入,修改后的SpringConfigurationApplication如下:

public class SpringConfigurationApplication {

    public static void main(String[] args) {

        ApplicationContext context = 
          new ClassPathXmlApplicationContext("applicationContext.xml");
    }
}

输出:

myBean Initialized
generate MyBean Instance

基于ComponentScan() 来获取Bean的定义

@Configuration 使用@Component 进行原注解,因此@Configuration 类也可以被组件扫描到(特别是使用XML元素)。

在这里认识几个注解: @Controller, @Service, @Repository, @Component

  • @Controller: 表明一个注解的类是一个"Controller",也就是控制器,可以把它理解为MVC 模式的Controller
    这个角色。这个注解是一个特殊的@Component,允许实现类通过类路径的扫描扫描到。它通常与@RequestMapping
    注解一起使用。

  • @Service: 表明这个带注解的类是一个"Service",也就是服务层,可以把它理解为MVC
    模式中的Service层这个角色,这个注解也是一个特殊的@Component,允许实现类通过类路径的扫描扫描到

  • @Repository: 表明这个注解的类是一个"Repository",团队实现了JavaEE 模式中像是作为"Data Access Object" 可能作为DAO来使用,当与 PersistenceExceptionTranslationPostProcessor结合使用时,这样注释的类有资格获得Spring转换的目的。这个注解也是@Component 的一个特殊实现,允许实现类能够被自动扫描到

  • @Component: 表明这个注释的类是一个组件,当使用基于注释的配置和类路径扫描时,这些类被视为自动检测的候选者。

也就是说,上面四个注解标记的类都能够通过@ComponentScan 扫描到,上面四个注解最大的区别就是使用的场景和语义不一样,比如你定义一个Service类想要被Spring进行管理,你应该把它定义为@Service 而不是@Controller因为我们从语义上讲,@Service更像是一个服务的类,而不是一个控制器的类,@Component通常被称作组件,它可以标注任何你没有严格予以说明的类,比如说是一个配置类,它不属于MVC模式的任何一层,这个时候你更习惯于把它定义为 @Component。@Controller,@Service,@Repository 的注解上都有@Component,所以这三个注解都可以用@Component进行替换。

来看一下代码进行理解:

定义五个类,类上分别用@Controller, @Service, @Repository, @Component, @Configuration 进行标注,分别如下

@Component
public class UserBean {}

@Configuration
public class UserConfiguration {}

@Controller
public class UserController {}

@Repository
public class UserDao {}

@Service
public class UserService {}

在MyConfiguration上加上@ComponentScan 注解,扫描上面5个类所在的包位置。代码如下:

@Configuration
@ComponentScan(basePackages = "com.spring.configuration.pojo")
public class MyConfiguration {

    @Bean
    public MyBean myBean(){
        System.out.println("myBean Initialized");
        return new MyBean();
    }
}

修改 SpringConfigurationApplication 中的代码,如下:

public class SpringConfigurationApplication {

    public static void main(String[] args) {

//        AnnotationConfigApplicationContext context = = new AnnotationConfigApplicationContext(MyConfiguration.class)
//        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MyConfiguration.class);
        context.refresh();

        // 获取启动过程中的bean 定义的名称
        for(String str : context.getBeanDefinitionNames()){
            System.out.println("str = " + str);
        }
        context.close();

    }
}

输出:

myBean Initialized
generate MyBean Instance
str = org.springframework.context.annotation.internalConfigurationAnnotationProcessor
str = org.springframework.context.annotation.internalAutowiredAnnotationProcessor
str = org.springframework.context.annotation.internalRequiredAnnotationProcessor
str = org.springframework.context.annotation.internalCommonAnnotationProcessor
str = org.springframework.context.event.internalEventListenerProcessor
str = org.springframework.context.event.internalEventListenerFactory
str = myConfiguration
str = userBean
str = userConfiguration
str = userController
str = userDao
str = userService
str = myBean

由输出可以清楚的看到,上述定义的五个类成功被@ComponentScan 扫描到,并在程序启动的时候进行加载。

@Configuration 和 Environment

@Configuration 通常和Environment 一起使用,通过@Environment 解析的属性驻留在一个或多个"属性源"对象中,@Configuration类可以使用@PropertySource,像Environment 对象提供属性源

为了便于测试,我们引入junit4和spring-test 的依赖,完整的配置文件如下

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.spring.configuration</groupId>
    <artifactId>spring-configuration</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-configuration</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring.version>5.0.6.RELEASE</spring.version>
        <spring.test.version>4.3.13.RELEASE</spring.test.version>
        <junit.version>4.12</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.test.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在config 包下定义一个 EnvironmentConfig 类,注入Environment 属性,完整代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = EnvironmentConfig.class)
@Configuration
@PropertySource("classpath:beanName.properties")
public class EnvironmentConfig {

    @Autowired
    Environment env;

    @Test
    public void testReadProperty(){
        // 获取bean.name.controller 的属性
        System.out.println(env.getProperty("bean.name.controller"));
        // 判断是否包含bean.name.component
        System.out.println(env.containsProperty("bean.name.component"));
        // 返回与给定键关联的属性值
        System.out.println(env.getRequiredProperty("bean.name.service"));
    }
}

在/resources 目录下新建beanName.properties 文件,如下:
bean.name.configuration=beanNameConfiguration
bean.name.controller=beanNameController
bean.name.service=beanNameService
bean.name.component=beanNameComponent
bean.name.repository=beanNameRepository

启动并进行Junit测试,输出如下:

…………

beanNameController

true

beanNameService

…………

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值