1.Hello用注解来实现
- Hello类,采用@Component注解
package com.spring.annotation;
import org.springframework.stereotype.Component;
/**
*采用注解开发bean
* @Component用于类级别注解
*/
@Component
public class Hello {
public String getHello(){
return "Hello Word";
}
}
- HelloApp类,采用@ComponentScan注解
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());
}
}
-
运行结果
image
2.Student和Phone的例子用注解实现
- Lombok插件的使用
1)Settings->plugins,搜索Lombok,安装,重启IDEA
2)添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
- 使用@Data注解
- Phone类
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;
}
- Student类
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;
- StuentApp类
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);
}
}
-
运行结果
image
网友评论