作者:646579262 | 来源:互联网 | 2023-10-17 11:53
基于注解的DI注入1.导包环境搭建:导入aop包(spring-aop-4.1.6.RELEASE.jar)2.创建类3.创建spring.xml配置文件(必须在src目录下)该配
基于注解的DI注入
1.导包
环境搭建:导入aop包(spring-aop-4.1.6.RELEASE.jar)
2.创建类
3. 创建spring.xml配置文件(必须在src目录下)
spring.xml: 添加配置扫描组件
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">
4. 在类上添加注解
@Component
public class User implements Serializable {
@Value("张三")
private String name;
@Value("18")
private int age;
@Autowired
private Account account;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
@Override
public String toString() {
return "User{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
", account=" + account +
‘}‘;
}
}
@Component
public class Account implements Serializable {
@Value("111")
private int aid;
@Value("20000")
private double balance;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"aid=" + aid +
", balance=" + balance +
‘}‘;
}
}
运行代码:
public class Demo {
@Test
public void getUser(){
//获取spring配置文件生成的对象
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
//通过bean的id,获取bean对象
User user = (User)ac.getBean("user");
System.out.println(user);
}
}
运行结果:
5. 总结
spring中常用的几个注解
@Component:表示当前修饰的类交给Spring容器管理
- 如果类名上没加别名,则容器中的类id为类名的首字母小写名: User user = (User)ac.getBean("user");
- 如果加别名@Component("tuser"),则容器中的id为tuser: User user = (User)ac.getBean("tuser");
与@Component相同功能的还有三个衍生注解,都是用来修饰类:
@Repository:添加在Dao实现类上
@Service:添加在Service实现类上
@Controller:添加在Controller类上
给基本类型属性注入值使用@Value("..")
可以放在属性上,也可以放在setXXX(..)方法上
给引用类型属性注入值,使用
Bean作用范围的注解
@Scope 不写默认为singleton
singleton :默认是单例(常用)
prototype :原型模式(常用)
6.对比xml和注解方式区别