spring5 入门(四)使用注解开发
首先使用注解开发,必须在xml中导入context约束,下列代码红色部分,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context ="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
</beans>
之前我们都是在xml中同过bean注册一个类,现在可以直接通过@Component通过这个注解,进行注册,代码如下:
@Component
public class Teacher {
@Value("xxxxx")
private String name;
@Autowired
private Student student;
public Teacher() {
}
其中可以通过@Value这个注解进行变量值的注入,整个操作代替了bean注册的操作,当使用@Component注解的类要被xml文件扫描到,需要配置对应扫描路径
之所以要这样配,是因为我们的上下文对象是,是通过xml文件这个resource源有参构造出来的,对应扫描配置如下:
<context:component-scan base-package="com.hys.pojo"/>
@Component衍生了三个注解,这三个注解的功能和@Component一模一样
为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。
-
@Controller:web层
-
@Service:service层
-
@Repository:dao层
写上这些注解,就相当于将这个类交给Spring管理装配了!
XML与注解比较
-
XML可以适用任何场景 ,结构清晰,维护方便
-
注解不是自己提供的类使用不了,开发简单方便
xml与注解整合开发 :推荐最佳实践
-
xml管理Bean
-
注解完成属性注入
-
使用过程中, 可以不用扫描,扫描是为了类上的注解
基于java类进行配置,上面所述的上下文对象除了使用源文件,可以通过java配置类构建出来:
一个是基于java配置类
一个是基于xml文件
ApplicationContext context = new AnnotationConfigApplicationContext(studengconfig.class);
ApplicationContext context2 = new ClassPathXmlApplicationContext("bean.xml");
基于java配置类,完全可以省去了xml配置文件,在spring-boot中基本都是这样的!代码如下:
@Configurable代表了这个类表示为对应bean.xml文件
@Bean即文件中的bean属性 ,该方法的返回值类型,代表对应类,方法名代表对应id
@Import(MyConfig2.class) 表示导入其他配置类,相当于xml文件中的import标签
@ComponentScan("com.hys.pojo") 表示扫描使用了@Component的类,进行bean注册
@Configurable
@Import(MyConfig2.class)
@ComponentScan("com.hys.pojo") public class studengconfig { @Bean public Student student(){ return new Student(); } }

浙公网安备 33010602011771号