spring5 ioc 管理bean 注解

1.注解种类

@Component(value="student")
@Service
@Repository
@Controller

 

2.使用注解扫描包

<context:component-scan base-package="com.cj"></context:component-scan>
package com.cj.spring5;

import org.springframework.stereotype.Component;
@Component(value="student")
public class Student {
    private String name;

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

 2.1 只扫描指定注解

   <context:component-scan base-package="com.cj" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>

3. 属性的自动装配

3.1 注解

@Autowired 根据类型
@Qualifier 根据名称,要和Autowired一起使用
@Resource 结合
@Value 注入普通属性
@Component
public class UserService {

    @Autowired
    @Qualifier
    @Resource
    private UserDao userDao;

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

 4 完全注解开发

4.1创建配置类

package com.cj.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.cj.spring5")
public class SpringConfig {
}

4.2加载配置类

@Test
public void test4(){
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    //获取对象
    UserService userService = ctx.getBean("userService", UserService.class);
    //调用
    userService.add();
}

 

 
posted @ 2022-08-19 17:27  写代码的小哥哥  阅读(28)  评论(0)    收藏  举报