美文网首页
2019-03-01

2019-03-01

作者: 王杰磊 | 来源:发表于2019-03-01 22:21 被阅读0次

1.HelloWorld的例子采用注解来写

  • hello用@component来写
package com.spring.annotation;
import org.springframework.stereotype.Component;
@Component
public class Hello {
    public String getHello(){
        return "Hello World";
    }
}
  • HelloApp用@ComponentScan来写
package com.spring.annotation;
/**
 * 用于寻找@component注解标注bean
 */

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class HelloApp {
    public static void main(String[] args) {
        //通过注解创建上下文对象
        ApplicationContext context=new AnnotationConfigApplicationContext(HelloApp.class);
        //2.读取bean
        Hello hello=context.getBean(Hello.class);
        //3.运行
        System.out.println(hello.getHello());
    }
}
  • 运行结果


    image.png

2.改写Student和Phone类

2.1lombok插件使用

  • Settings->plugins,搜索Lombok,安装,重启IDEA
  • 添加依赖
 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

2.2使用@Data注解(不用再写构造方法,Setter/Getter方法和toString()方法了)

  • Phone类
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 采用注解和Lombok开发的phone
 */
@Component
@Data
public class Phone {
    @Value("iphoneX")
    private String brand;

    @Value("6666.6")
    private double price;
}
  • Student类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class Student {
    @Value("Tom")
    private String name;

    @Value("22")
    private int age;

    @Autowired
    private Phone phone;
}
  • StudentApp类
package com.spring.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class StudentApp {
    public static void main(String[] args) {
        ApplicationContext context=new AnnotationConfigApplicationContext(StudentApp.class);
        Student student=context.getBean(Student.class);
        System.out.println(student);
    }
}
  • 运行结果


    image.png

相关文章

网友评论

      本文标题:2019-03-01

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