spring1

作者: 蜗牛写java | 来源:发表于2018-09-24 23:35 被阅读0次

spring容器重要的特性就是IOC(控制反转)和DI(依赖注入)
控制反转:解决对象创建的问题;即对象创建交给了容器
依赖注入:在创建对象后,对象关系的处理就是依赖注入;或者组件之间的关系通过容器自动装配(依赖注入)

导入依赖

pom.xml

<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>

  <groupId>com.dwb.spring</groupId>
  <artifactId>dwb-spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>dwb-spring</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
  </dependencies>

</project>
配置类
@Configuration  //告诉Spring 这是一个配置类
public class MainConfig {
    //给容器注册一个Bean;类型为返回值的类型,id默认是用方法名
    @Bean("person")
    public Person person01() {
        return new Person("lisi", 20);
    }
}
测试类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
        
        String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String name : beanNamesForType) {
            System.out.println(name);
        }```

相关文章

  • spring1

    spring容器重要的特性就是IOC(控制反转)和DI(依赖注入)控制反转:解决对象创建的问题;即对象创建交给了容...

  • Spring学习-2

    引言:本篇文章是紧接着上一篇文章Spring1做的学习笔记,主要用来供自己复习; 一:spring注解配置方式(I...

网友评论

      本文标题:spring1

      本文链接:https://www.haomeiwen.com/subject/ytzhoftx.html