一、导包(添加依赖)
在Spring4之后,想要使用注解就必须要导入spring-aop这个包,这里我直接添加的spring-webmvc,其中包含了我们需要的包。
maven:spring-webmvc
<dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>5.3.23version> dependency>
二、在xml文件中添加注解的约束,增加对注解的支持
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"> <context:annotation-config/> <context:component-scan base-package="com.jms"/> beans>
三、Bean的注入
package com.jms.pojo; import org.springframework.stereotype.Component; //等价于<bean id="user" class="com.jms.pojo.User"/> @Component(value = "user") public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
使用@Component注解,value是相当于id,可以不设置,这里默认是user。
测试一下:
@Test
public void test1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user.getName());
}
四、属性值的注入
//等价于
@Value("jms")
private String name;
使用@Value(“”)注解,这个注解也可以用在set方法。
测试如下:
五、作用域的注入
@Scope("singleton")
public class User {}
六、衍生的注解
@Component有几个衍生的注解,分别用于不同的分层中。
dao层:
@Repository
public class UserDao {}
service层:
@Service
public class UserService {}
Contorller层:
@Controller
public class UserController {}
这四个注解功能相同,都是将类注册到Spring容器中。
七、小结
xml与注解各有千秋,xml更加万能,适用于任何场合,维护起来更加方便;注解在简单的使用中要比xml更加简便,但复杂的配置还是xml更合适。
xml和注解的最佳实践:xml用来管理Bean,注解只负责属性的注入。
Original: https://www.cnblogs.com/jmsstudy/p/16730159.html
Author: 谁知道水烫不烫
Title: Spring(十一):使用注解开发
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/616428/
转载文章受原作者版权保护。转载请注明原作者出处!