Bean管理-注解方式创建对象与属性注入

需要开启包扫描 注解标注的类才能被创建

创建对象的注解:

1.@Controller  --常用在web层

2.@Service  --常用在service层

3.@Repository  --常用在dao层

4.@Component  --普通的组件

以上注解功能一样,都可以创建bean实例

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">
    <!--开启包扫描-->
    <context:component-scan base-package="com.xxx.spring"></context:component-scan>
</beans>

 

package com.xxx.spring.service;

import org.springframework.stereotype.Service;

@Service("userService")//属性值可以不写,不写会默认userService
public class UserService {

    public void add(){
        System.out.println("service add...");
    }
}

测试代码

import com.alibaba.druid.pool.DruidDataSource;
import com.xxx.spring.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestCase {


    @Test
    public void testAnno(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);

    }
}

 

注入属性的注解:

1.@Autowired --根据属性类型进行注入

2.@Qualifier  --根据属性名称进行注入,当接口存在多个实现类时,可以指定具体名称

 

 

 

 

 

 

 

posted @ 2023-02-09 21:29  Mr_sven  阅读(35)  评论(0编辑  收藏  举报