javaEE架构程序设计-Spring IOC容器_注解配置方式

Spring IOC容器_注解配置方式

  1. 常用的注解
    (1)在容器器定义bean
    @Repository 仓库
    @Service 服务
    @Controller 控制器
    @Component 组件

从编程的角度讲,无论采用哪一种注解方式,都是定义了一个bean,仅仅是逻辑含义不同而已从编程的角度讲,无论采用哪一种注解方式,都是定义了一个bean,仅仅是逻辑含义不同而已

(2)DI,对象成员的初始化
@Resource 对象
@Value 基本数据类型,字符串,数值型,int

  1. 使用注解 编程思路
    (1)pom.xml文件中引入spring-context框架
    (2)在applicationContext.xml中设置注解支持
    (3)使用注解,让spring容器,自动的创建对象

  2. 创建项目
    spring02
    创建了包 gyh.yogurt.spring02
    创建类 Application

  3. 引入spring-context

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.1.20.RELEASE</version>
</dependency>
  1. 配置spring容器配置类,applicationContex.xml
    配置注解
<context:component-scan base-package="yzg.kc2021.spring02"></context:component-scan>
  1. 以注解的方式创建bean

(1)创建接口

IStudent

public interface IStudent {
    public void Create();       // 创建
}

(2)创建类Student,同时,在类的定义中,应用注解,创建bean

@Repository("s1")
public class Student implements IStudent {
    public void Create() {
        System.out.println("Student对象创建..." + this);
    }
}

引入ID(依赖注入后)

//@Repository("s1")
@Component("s1")
public class Student implements IStudent {

    @Value("zhangsan")
    private String name = "";       //  姓名

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void Create() {
        System.out.println("Student(" + name + ")对象创建..." + this);
    }
}
posted @ 2021-03-23 17:31  酸奶面包  阅读(53)  评论(0编辑  收藏  举报