spring使用注解开发
使用注解开发必须引入aop
的包.
在配置文件当中必须引入一个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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
原始方式都是使用
bean
的标签进行bean
注入,但是在实际开发中一般都会使用注解开发.
- 配置扫描哪些包下的注解.
<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>
- 在指定的包下编写类,增加注解.
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
public String name = "秦疆";
}
测试:
@Test
public void test(){
ApplicationContext applicationContext =new ClassPathXmlApplicationContext("beans.xml");
User user = (User) applicationContext.getBean("user");
System.out.println(user.name);
}
属性注入:
使用注解注入属性:
可以不用提供set
方法,直接在属性名上添加@value("值")
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
@Value("秦疆")
// 相当于配置文件中 <property name="name" value="秦疆"/>
public String name;
}
如果提供了set
方法,在set
方法上添加@value("值")
:
@Component("user")
public class User {
public String name;
@Value("秦疆")
public void setName(String name) {
this.name = name;
}
}
备注:文章内容大都来自狂神笔记.