day02-02 采用注解方式开发bean

2019-03-01  本文已影响0人  黑桃_06ea

1.Student和Phone用注解实现

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

3)使用@Data注解,简化POJO类,不用再写那些构造方法、getter/setter,toString()了,专注定义属性即可。

package com.spring.one;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Data
public class Phone {
    //通过@Value注解给简单类型赋值
    @Value("iPhoneX")
    private String brand;
    @Value("666.6")
    private Double prise;
}
package com.spring.one;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class PhoneApp {
    public static void main(String[] args){
        ApplicationContext context=new AnnotationConfigApplicationContext(PhoneApp.class);
        Phone phone=context.getBean(Phone.class);
        System.out.println(phone);
    }
}
package com.spring.one;
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("WangJie")
    private String name;
    @Value("21")
    private int age;
    // 引用类型,通过@Autowired注入Phone的bean
    @Autowired
    private Phone phone;
}
package com.spring.one;
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);
    }
}
<!-- log4j日志依赖 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

注解拓展:

上一篇下一篇

猜你喜欢

热点阅读