文章目录
注解创建对象的入门程序
- 创建实体类,注解标明,用于创建对象
@Component
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao ;
public AccountServiceImpl(){
System.out.println("对象创建了");
}
public void saveAccount(){
accountDao.saveAccount();
}
}
- 在resources下的xml文件中配置,告知spring在创建容器时要扫描的包,否则spring不知道你哪些地方有注解
<?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.itheima"></context:component-scan>
</beans>
- 获取对象并使用
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取Bean对象
IAccountService as = (IAccountService)ac.getBean("accountServiceImpl");
System.out.println(as);
}
用于创建对象的注解
@Component
作用:
用于把当前类对象存入spring容器中
属性:
value:用于指定bean的id,当我们不写的时候,默认为,当前类名且首字母该小写
@Controller:表现层
@Service:业务层
@Repository:持久层
以上三个注解和@Component完全一样,只是让我们分清层次
用于创建对象的注解例子
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
public void saveAccount(){
System.out.println("保存了账户11111111");
}
}
用于注入数据的注解
注入bean类型的注解
下面介绍的三个注入都只能注入其他bean类型的数据,基本类型和String类型无法使用以下注解注入,另外,集合类型的注入只能通过xml实现
他们作用和xml配置文件中bean标签中写一个<property></property>标签作用一样
@Autowired
-
作用:
自动按照类型注入
只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以成功注入
如果容器中有多个类型匹配,查看@Autowired修饰的变量是否与某个bean的id相同,相同则注入,否则,报错 -
出现位置:变量和方法上
-
细节:注解注入时,set不是必须的了
@Qualfier
- 在按照类注入的基础上再按照名称注入
- 他在给类成员注入时不能单独使用,但是给方法参数注入时可以
- 属性:
value:指定bean的id
@Resource
- 作用:直接按照bean的id注入,它可以独立使用
- 属性:
name:用于指定bean的id
数据注入例子
下面的两个代码表达的意思相同,类成员aDao的初始化,去spring容器中寻找有没有id=accountDao的对象,有则注入
@Component
public class AccountServiceImpl implements IAccountService {
@Resource(name="accountDao")
private IAccountDao aDao ;
}
@Component
public class AccountServiceImpl implements IAccountService {
@Autowired
@Qualifier("accountDao")
private IAccountDao accountDao ;
}
注入基本数据类型和String类型的注解
@Value
- 作用:用于注入基本数据类型和String类型
- 属性:
value:用于指定数据的值。它可以使用SpEL(spring中el表达式),SpEL的写法 :${表达式}
用于改变作用范围的注解
作用:作用和bean标签中scope属性一样
@Scope
- 作用:用于指定bean的作用范围
- 属性:
value:指定范围的取值,常用取值:singleton prototype
与生命周期相关的注解
@PostConstruct
指定初始化方法
@PreDestroy
指定销毁方法