采用注解开发bean

2019-03-02  本文已影响0人  国王兔子

1.Hello用注解来实现

package com.spring.annotation;

import org.springframework.stereotype.Component;

/**
 *采用注解开发bean
 * @Component用于类级别注解
 */
@Component
public class Hello {
    public String getHello(){

        return "Hello Word";
    }
}
package com.spring.annotation;

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);
        HelloWorld  helloWorld = context.getBean(HelloWorld.class);
        System.out.println(helloWorld.getHello());
    }
}

2.Student和Phone的例子用注解实现

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

  1. 使用@Data注解
package com.spring.annotation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 采用注解Lombok开发的Phone类
 * Created by HP on 2019/2/28.
 */
@Component
public class Phone {
    @Value("iPhoneX")
    private String brand;
    @Value("6666.6")
    private double price;

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

/**
 * Created by HP on 2019/2/28.
 */
@Component
@Data
public class Student {
    @Value("Tom")
    private String name;
    @Value("21")
    private String 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;

/**
 * Created by HP on 2019/2/28.
 */
@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);
}
}
上一篇 下一篇

猜你喜欢

热点阅读