spring注解将类注入到ioc容器
四大注解的作用 :以下四个注解能快速的将bean加载到ioc容器当中,不需要和以前一样,再xml的beans中创建bean的形式来加入。@Repository:该注解主要针对于数据访问层的(Dao,持久化层)@Service:该注解主要针对于业务逻辑层(service层)@Controller:该注解主要针对于控制器层(servlet层 ,Controller层)@Comp...
·
四大注解的作用 :以下四个注解能快速的将bean加载到ioc容器当中,不需要和以前一样,再xml的beans中创建bean的形式来加入。
-
@Repository:该注解主要针对于数据访问层的(Dao,持久化层)
-
@Service:该注解主要针对于业务逻辑层(service层)
-
@Controller:该注解主要针对于控制器层(servlet层 ,Controller层)
-
@Component:该注解不属于任何层,当该类不知道属于以上三类的那一类时可以使用该注解。
以上都是推荐使用,这样更加显而易见每个类的功能,当然也可以随便添加作用还是存在的。
加入到ioc容器的步骤
- 创建类 ,再每个类上添加对应的注解
- 导入context命名空间,扫描其注解所再的包再ioc容器当中。
- 如果工厂是导入jar包的形式,那么一定要导入spring aop 的包,aop 包支持添加注解形式
- 需要得到bean时,bean的ID就是注解类的首字母小写。
项目架构
maven
<dependencies>
<!-- spring 核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- 日志包-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 单元测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
</dependency>
</dependencies>
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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描com.stone.dome包下的所有注解 -->
<context:component-scan base-package="com.stone.dome"/>
</beans>
类
@Repository
public class BookDao
{
private int a = 15 ;
public int getA()
{
return a;
}
public void setA(int a)
{
this.a = a;
}
}
测试
public class SpringIocDome2
{
private ApplicationContext ioc =new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void test1(){
BookDao bookDao = ioc.getBean("bookDao", BookDao.class);
int a = bookDao.getA();
System.out.println(a);
}
}
运行结果
使用注解的模式加入bean到ioc容器的注意点 :
- bean的id就是类的首字母小写
- bean的作用域默认为单例 singleton。
如何修改注解形式的bean的id 和 作用域
修改id的二种方式
- 注解的后面添加小括号(),小括号类添加双引号再引号类写入需要修改的名字
- 再第一种方式的基础上,再小括号类添加value
修改作用域的二种方式
1 . 再类上再添加@Scope注解,并再注解的后面添加小括号(),小括号类添加双引号再引号类写入需要修改的名字
2 .再第一种方式的基础上,再小括号类添加value
更多推荐
已为社区贡献2条内容
所有评论(0)