1. HelloWorld的例子改成用注解来实现
-
HelloWorld类,采用@Component注解
package com.spring.annotation; import org.springframework.stereotype.Component; @Component public class HelloWorld { public String getHello() { return "Hello World"; } }
-
HelloWorldApp类,采用@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()); } }
-
运行结果
2、Student和Phone的例子改成用注解的方法实现
-
Lombok插件的使用
打开Settings,选择Plugins,搜索Lombok,安装,重启IDEA
添加依赖<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency>
-
Phone类
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("iPhoneX") private String brand; @Value("6666.66") 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; @Component @Data public class Student { @Value("Tom") private String name; @Value("20") private int age; //使用@Autowired注入一个Phone类型的bean @Autowired private Phone phone; }
-
StudentApp类
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); } }
-
运行结果