4. 采用注解方式开发bean

2019-03-01  本文已影响0人  叶小慈呀

1.传统的Spring做法

1.1两种做法

1.2缺点

2.Spring常用注解总结

3.HelloWorld的例子改成用注解来实现

package com.spring.annotation;
/**
 * 采用注解开发的bean
 */
import org.springframework.stereotype.Component;
/**
 * @component用于类级别注解,标注本类为一个可被Spring容器托管的bean
 */
@Component
public class HelloWorld {
    public String getHello(){
        return  "Hello World";
    }
}

package com.spring.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**@ComponentScan
 * 用于寻找用@ComponentScan注解标注的bean
 */
@ComponentScan
public class HelloWorldApp {
    public static void main(String[] args) {
        //1.通过注解创建上下文
        ApplicationContext context = new AnnotationConfigApplicationContext     (HelloWorldApp.class);
        //2.读取bean
        HelloWorld hello = context.getBean(HelloWorld.class);
        //3.运行
        System.out.println(hello.getHello());
  }
}
运行结果

4.Student和Phone改成注解形式

<!--Lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>
package com.spring.annotation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * 采用注解和Lombok开发的Phone类
 */
@Component
@Data
public class Phone {
    //通过@Value注解给简单类型赋值
    @Value("三星")
    private  String brand;
    @Value("4000.06")
    private double prize;
}
package com.spring.annotation;
import lombok.Data;
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("Lily")
    private String name;
    @Value("20")
    private int age;
    //引用类型,通过@Autowired注入Phone的bean
    @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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读