Sping5学习(四):IOC操作Bean管理 之 基于注解方式的对象创建

61 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情

1、什么是注解

先看官方的解释:
**Spring Annotations** are a form of metadata that provides data about a program. 
Annotations are used to provide supplemental information about a program. It does 
not have a direct effect on the operation of the code they annotate. It does not 
change the action of the compiled program.

总结一下:

(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)

(2)使用注解,注解作用在类上面,方法上面,属性上面

(3)使用注解目的:简化 xml 配置

2、Spring 针对 Bean 管理中创建对象提供注解

  • @Required
  • @Autowired
  • @Configuration
  • @ComponentScan
  • @Bean
  • @Component
  • @Controller
  • @Service
  • @Repository, etc.
  • 上面四个注解功能是一样的,都可以用来创建 bean 实例 具体步骤: 1、首先引入jar包

image.png

2、开启组件扫描

我的类写在src下的demo02中,所以应该这样写xml文件

bean2.xml:(xmlns中的值可以直接复制上面的,然后改一下)

<?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">
 
<!--    开启组件扫描-->
    <context:component-scan base-package="demo02"></context:component-scan>
    
</beans>

3、创建类,在类上面添加注解

package demo02;
 
import org.springframework.stereotype.Component;
 
@Component
public class UserService {
 
    public void add(){
 
        System.out.println("hhh");
    }
}

注意,Componet后可以跟value值,也可省略不写。如果省略,默认为类名首字母小写

比如UserService类,默认为userService

4、测试

/**
     * 测试注解方式
     */
    @Test
    public void testService(){
 
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
 
        System.out.println(userService);
        userService.add();
    }

运行结果如下:

image.png