Java笔记:Spring配置xml和注解(5)

简介: Java笔记:Spring配置xml和注解

包扫描

1、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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>
    <!--开启包扫描-->
    <context:component-scan base-package="com.demo.ioc"/>
</beans>

2、注解方式

package com.demo.ioc;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// 创建配置文件,可以认为是一个xml配置文件
@Configuration
// 设置需要扫描的包
@ComponentScan(value = "com.demo.ioc")
public class MyConfiguration {
}
package com.demo.ioc;
import org.springframework.stereotype.Component;
// 增加注解后会被Spring扫描到, 默认的Id是类名首字母小写
@Component(value = "person")
public class Person {
}

Bean别名

xml形式

<bean id="person" name="person1, person2" class="com.demo.ioc.Person"/>
<alias name="person" alias="person3"/>

注解方式

package com.demo.ioc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 创建配置文件,可以认为是一个xml配置文件
@Configuration
public class MyConfiguration {
    @Bean(name = {"person1", "person2"})
    public Person person(){
        return new Person();
    }
}

通过注解注入Bean

  • 通过方法注入Bean
  • 通过构造方法注入Bean
  • 通过Set方法注入Bean
  • 通过属性注入Bean
  • 集合类Bean类型注入
  • 直接注入集合实例
  • 将多个泛型的实例注入到集合
  • 将多个泛型实例注入到List
  • 控制泛型示实例在List中的顺序
  • 将多个泛型的实例注入到Map
  • String、Integer等类型直接赋值
  • SpringIoC容器内置接口示例注入

准备Bean

package com.demo.ioc;
import org.springframework.stereotype.Component;
@Component
public class Cat {
}
package com.demo.ioc;
import org.springframework.stereotype.Component;
@Component
public class Dog {
}
package com.demo.ioc;
import org.springframework.stereotype.Component;
@Component
public class Pig {
}

配置文件

package com.demo.ioc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 创建配置文件,可以认为是一个xml配置文件
@Configuration
@ComponentScan(value = "com.demo.ioc")
public class MyConfiguration {
    @Bean(name = "stringList")
    public List<String> stringList() {
        List<String> list = new ArrayList<>();
        list.add("Tom");
        list.add("Jack");
        return list;
    }
    // 此优先级高于 List<String>
    @Bean
    @Order(2) // 指定优先级
    public String string1(){
        return "string1";
    }
    @Bean
    @Order(1)
    public String string2(){
        return "string2";
    }
    @Bean
    public Map<String, Integer> stringIntegerMap(){
        Map<String, Integer> map = new HashMap<>();
        map.put("dog", 23);
        map.put("pig", 24);
        return map;
    }
    // 优先级高于 Map<String, Integer>
    @Bean
    public Integer integer1(){
        return 222;
    }
    @Bean
    public Integer integer2(){
        return 223;
    }
}

注入实例

package com.demo.ioc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
public class Person {
    private Dog dog;
    // 1、构造方法注入
    @Autowired
    public Person(Dog dog) {
        this.dog = dog;
    }
    private Cat cat;
    // 2、Set方法注入
    @Autowired
    public void setCat(Cat cat) {
        this.cat = cat;
    }
    // 3、通过属性注入
    @Autowired
    private Pig pig;
    private List<String> stringList;
    // 4、注入List类型
    @Autowired
    // 指定Bean的ID
    // @Qualifier(value = "stringList")
    public void setStringList(List<String> stringList) {
        this.stringList = stringList;
    }
    public List<String> getStringList() {
        return stringList;
    }
    // 5、Map类型注入
    private Map<String, Integer> stringIntegerMap;
    public Map<String, Integer> getStringIntegerMap() {
        return stringIntegerMap;
    }
    @Autowired
    public void setStringIntegerMap(Map<String, Integer> stringIntegerMap) {
        this.stringIntegerMap = stringIntegerMap;
    }
    private String name;
    // 6、String、Integer等类型直接赋值
    @Value("Tom") // 如果是Integer会自动转型
    public void setName(String name) {
        this.name = name;
    }
    // 7、容器内置接口注入
    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    public ApplicationContext getContext() {
        return context;
    }
    @Override
    public String toString() {
        return "Person{" +
                "dog=" + dog +
                ", cat=" + cat +
                ", pig=" + pig +
                ", stringList=" + stringList +
                ", stringIntegerMap=" + stringIntegerMap +
                ", name='" + name + '\'' +
                '}';
    }
}


测试

package com.demo.ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BeanTest {
    @Test
    public void testBean() {
        // 获取上下文
        ApplicationContext context =
                new AnnotationConfigApplicationContext(MyConfiguration.class);
        // 获取Bean
        Person bean = context.getBean("person", Person.class);
        System.out.println(bean);
        System.out.println(bean.getStringList());
        System.out.println(bean.getStringIntegerMap());
        System.out.println(bean.getContext().getBean("cat"));
    }
}

测试输出

Person{dog=com.demo.ioc.Dog@441772e, 
    cat=com.demo.ioc.Cat@7334aada, 
    pig=com.demo.ioc.Pig@1d9b7cce, 
    stringList=[string2, string1], 
    stringIntegerMap={integer1=222, integer2=223}, 
    name='Tom'
}
[string2, string1]
{integer1=222, integer2=223}
com.demo.ioc.Cat@7334aada
相关文章
|
8月前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
2121 1
|
8月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
453 0
|
11月前
|
XML Java 编译器
Java注解的底层源码剖析与技术认识
Java注解(Annotation)是Java 5引入的一种新特性,它提供了一种在代码中添加元数据(Metadata)的方式。注解本身并不是代码的一部分,它们不会直接影响代码的执行,但可以在编译、类加载和运行时被读取和处理。注解为开发者提供了一种以非侵入性的方式为代码提供额外信息的手段,这些信息可以用于生成文档、编译时检查、运行时处理等。
231 7
|
8月前
|
Java 编译器 开发者
注解的艺术:Java编程的高级定制
注解是Java编程中的高级特性,通过内置注解、自定义注解及注解处理器,可以实现代码的高度定制和扩展。通过理解和掌握注解的使用方法,开发者可以提高代码的可读性、可维护性和开发效率。在实际应用中,注解广泛用于框架开发、代码生成和配置管理等方面,展示了其强大的功能和灵活性。
203 25
|
10月前
|
存储 Java 开发者
【潜意识Java】深入详细理解分析Java中的toString()方法重写完整笔记总结,超级详细。
本文详细介绍了 Java 中 `toString()` 方法的重写技巧及其重要
568 10
【潜意识Java】深入详细理解分析Java中的toString()方法重写完整笔记总结,超级详细。
|
11月前
|
XML Java 数据格式
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
本文介绍了在使用Spring框架时,如何通过创建`applicationContext.xml`配置文件来管理对象。首先,在resources目录下新建XML配置文件,并通过IDEA自动生成部分配置。为完善配置,特别是添加AOP支持,可以通过IDEA的Live Templates功能自定义XML模板。具体步骤包括:连续按两次Shift搜索Live Templates,配置模板内容,输入特定前缀(如spring)并按Tab键即可快速生成完整的Spring配置文件。这样可以大大提高开发效率,减少重复工作。
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
|
10月前
|
前端开发 JavaScript Java
Java构建工具-maven的复习笔记【适用于复习】
这篇文档由「潜意识Java」创作,主要介绍Maven的相关知识。内容涵盖Maven的基本概念、作用、项目导入步骤、依赖管理(包括依赖配置、代码示例、总结)、依赖传递、依赖范围以及依赖的生命周期等七个方面。作者擅长前端开发,秉持“得之坦然,失之淡然”的座右铭。期待您的点赞、关注和收藏,这将是作者持续创作的动力! [个人主页](https://blog.csdn.net/weixin_73355603?spm=1000.2115.3001.5343)
284 3
|
11月前
|
安全 Java 编译器
Kotlin教程笔记(27) -Kotlin 与 Java 共存(二)
Kotlin教程笔记(27) -Kotlin 与 Java 共存(二)
|
11月前
|
Java 开发工具 Android开发
Kotlin教程笔记(26) -Kotlin 与 Java 共存(一)
Kotlin教程笔记(26) -Kotlin 与 Java 共存(一)
下一篇
oss云网关配置