2019-03-01

2019-03-01  本文已影响0人  王杰磊

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

package com.spring.annotation;
import org.springframework.stereotype.Component;
@Component
public class Hello {
    public String getHello(){
        return "Hello World";
    }
}
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());
    }
}

2.改写Student和Phone类

2.1lombok插件使用

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

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

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;
}
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;
}
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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读