0
点赞
收藏
分享

微信扫一扫

Spring-8-注解(对象的创建)


文章目录

  • ​​注解的di​​
  • ​​1.使用注解第一步加入maven的依赖(spring-context)​​
  • ​​2.在类里面加spring的注解​​
  • ​​创建对象1.@Context(value="对象名")==@Context("对象名")或者@Context 这里的对象名默认是类名的首字母小写​​
  • ​​创建对象2.@Repository(用在持久层的类上面)表示创建dao对象,dao对象是可以访问数据库的​​
  • ​​创建对象3.@Service用在业务层的类上面):放在service的实现类上面,是做事物的,可以有事务等功能​​
  • ​​创建对象4.@Controller(用在控制器类上面),创建控制器上面的,能接受参数,显示处理结果​​
  • ​​上面的和@Context使用语法相同,但是后三个还有额外功能,给项目对象分层的​​
  • ​​3.在配置文件中加入扫描器的标签​​
  • ​​1.使用多次组件扫描器​​
  • ​​2.使用分割符号;或者,分割多个包名​​
  • ​​3.使用指定的父包(不建议)​​

注解的di

1.使用注解第一步加入maven的依赖(spring-context)

<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>

2.在类里面加spring的注解

创建对象1.@Context(value=“对象名”)==@Context(“对象名”)或者@Context 这里的对象名默认是类名的首字母小写

创建对象2.@Repository(用在持久层的类上面)表示创建dao对象,dao对象是可以访问数据库的

创建对象3.@Service用在业务层的类上面):放在service的实现类上面,是做事物的,可以有事务等功能

创建对象4.@Controller(用在控制器类上面),创建控制器上面的,能接受参数,显示处理结果

上面的和@Context使用语法相同,但是后三个还有额外功能,给项目对象分层的

package org.example.ba01;

import org.springframework.stereotype.Component;

/**
* @compatent:创建对象的,等同于<bean>功能
*
* 属性value就是对象的名称,也就是bean的id值
* value值是唯一的,创建的对象在整个Spring容器中只有一个
* 位置:在类的是上面
* 等同于<bean id="myStudent" class="ba01.student" />
* 需要配置文件resource里面
*/
@Component(value = "myStudent")
public class Studnet {

private String name ;
private int age;

@Override
public String toString() {
return "Studnet{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

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;
}
}

3.在配置文件中加入扫描器的标签

1.使用多次组件扫描器

<context:component-scan base-package=“org.example.ba01”/>
<context:component-scan base-package=“org.example.ba02”/>
<context:component-scan base-package=“org.example.ba03”/>

2.使用分割符号;或者,分割多个包名

<context:component-scan base-package=“org.example.ba01;org.example.ba02;org.example.ba03”/>

3.使用指定的父包(不建议)

<context:component-scan base-package=“org.example”/>

<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--申明组件扫描器-->
<!--component-scan组件就是java对象 -->
<!--component-scan 的工作方式,Spring会按照 base-package的路径通过注解创建对象,或者给对象赋值 -->
<!--加入 component-scan这个和配置文件会加入一些东西 -->
<context:component-scan base-package="org.example.ba01"/>
</beans>

Spring-8-注解(对象的创建)_spring

主要学习的注解
1.@component
2.@Respotory
3.@Service
4.@Controller
5.@Value
6.@Resource


举报

相关推荐

0 条评论