spring注解自动装配实现

spring注解实现自动装配

1.搭建环境及具体实现步骤

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 https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config></context:annotation-config>
</beans>

2.常用依赖

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

3.需要使用到的注解说明

@Autowired:自动装配通过类型--名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="dog222")指定
@Nullable :字段标记了这个注解,说明这个字段 可能为null
@Resource:自动装配通过名字
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean
@Component等价于<bean id="user" class="com.nb.pojo.User"/>

4.自动装配

byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id,必须写id
byType:会自动在容器上下文中查找,和自己对象属性类型相同bean 保证类型全局唯一,可以不写id
byName:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
byType:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的set方法的值一致,并且这个bean需要和自动注入的属性的set方法的值一致
@Autowired:直接再属性上使用,也可以在set方式上使用
使用Autowired我们可以不用编写set方法 ,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
@Autowired(required = false)如果显示定义了Autowired的required值为false,说明这个对象可以为null,否则不能为null
@Nullable  字段标记了这个注解,说明这个字段 可能为null
@Resource 都是用来自动装配,都可以放在属性字段上
@Autowired 默认byType类型查找,找不到再byName
@Resource  默认通过byName查找,找不到再byType

自动装配步骤

1.导入约束
       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 https://www.springframework.org/schema/context/spring-context.xsd">
2.开启自动装配注解支持
       <context:annotation-config></context:annotation-config>
3.创建实体类
4.添加bean
5.使用@Autowired/@Resource完成注解开发

5.使用注解开发

在Spring4后,使用注解开发,必须保证aop的包导入了
1.bean
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean
@Component等价于<bean id="user" class="com.nb.pojo.User"/>
2.属性如何注入
@Value("小明")等价于property
<bean id="user" class="com.nb.pojo.User">
    <property name="name" value="小明"/>
</bean>-->

User类

@Component
public class User {

    public String name ;
    @Value("小明")
    public void setName(String name) {
        this.name = name;
    }
}

注解开发实例
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 https://www.springframework.org/schema/context/spring-context.xsd">
          
 <context:annotation-config></context:annotation-config>
    <bean id="cat" class="com.nb.pojo.Cat"/>
    <bean id="dog222" class="com.nb.pojo.Dog"/>
    <bean id="people" class="com.nb.pojo.People" autowire="byType"/>
</beans>

Cat类

public class Cat {
    public void shout(){
        System.out.println("喵喵喵");
    }
}

Dog类

public class Dog {
    public void shout(){
        System.out.println("汪汪汪");
    }
}

使用到的注解说明

@Autowired:自动装配通过类型--名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="dog222")指定
@Nullable :字段标记了这个注解,说明这个字段 可能为null
@Resource:自动装配通过名字
@Component:组件,放在类上,说明这个类被Spring管理了,就是bean

People类

public class People {
    @Resource(name="cat")
    private Cat cat;
//    @Autowired
//    @Qualifier(value="dog222")
    //byType--->byName
    //常用@Autowired
    @Resource(name="dog222")
    private Dog dog;
    private String name;

    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

测试类

public class MyTest {
    @Test
    public void  test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        People people = context.getBean("people", People.class);
        people.getCat().shout();
        people.getDog().shout();
    }
}

3.衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层 
    @dao        ---[@Repository]
    @service    ---[@Service]
    @controller ---[@Controller]
    这4个注解功能都是一样的,都是代表将某个类注册 到Spring中,装配bean

4.自动装配

@Autowired:自动装配通过类型--名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="dog222")指定
@Nullable :字段标记了这个注解,说明这个字段 可能为null
@Resource:自动装配通过名字

5.作用域

@Component
@Scope("singleton")//单例模式 prototype原型模式
public class User {

    public String name ;
    @Value("小明")
    public void setName(String name) {
        this.name = name;
    }
}

6.小结

xml与注解:
    xml更加万能,适用于任何场合!维护简单方便
    注解,不是自己的类,不能使用,维护相对复杂!
xml与注解最佳实践:
    xml用来管理bean
    注解只完成属性的注入
    我们在使用的过程中,只需要注意一个问题:必须让注解生效,开启注解主持

注解开发支持,扫描具体包下的所有注解

 <!--指定要扫描的包,这个包下的注解就会生效-->
<beans>
    <context:component-scan base-package="com.nb"/>
    <context:annotation-config/>
</beans>

2.完全基于Java的方式配置Spring

实体类

//这个类被Spring管理,注册到了容器中
@Controller
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value("小红")//属性注入值
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置类/配置文件

@Configuration
@ComponentScan("com.nb.pojo")
@Import(MyConfig2.class)
//这个 也会被Spring容器托管,注册到容器中,
//因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看的beans.xml
//@ComponentScan("com.nb.pojo")扫描包
//@Import(MyConfig2.class)引入另一个配置类
public class MyConfig {
    //注册一个bean,就相当于我们之前写的一个bean标签,id就相当于方法名
    //方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();//返回要注入到bean的对象
    }
}

第二个配置类

@Configuration
@ComponentScan("com.nb.pojo")
//这个 也会被Spring容器托管,注册到容器中,
//因为他本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看的beans.xml
//@ComponentScan("com.nb.pojo")扫描包
public class MyConfig2 {
    //注册一个bean,就相当于我们之前写的一个bean标签,id就相当于方法名
    //方法的返回值,就相当于bean标签中的class属性
}

测试类

public class MyTest {
    @Test
    public void test(){
        //如果完全使用配置类方式做,只能通过ApplicationContext上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

这种纯Java的配置方式,在SpringBoot中随处可见!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值