Spring(四)之注解注入

注解注入创建对象

spring的注解注入是比较常用的方式

  1. Component(与下面三者的用处基本一致)
  2. Controller(表现层)
  3. Service(业务层)
  4. Repository(持久层)

在使用注解先需要先修改原来bean.xml的配置信息

<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-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<!--  注解形式  -->
    <context:component-scan base-package="imis"></context:component-scan>
</beans>

首先介绍第一个注解Component

/**Component
    作用:用于把当前类对象存入spring容器中
    属性:
        value:用于指定bean的id,当不写时,默认为当前的类名,首字母改为小写
 */
@Component
public class UserServiceImpl implements IUserService {
    
    
    private String name;
    private Integer age;
    private Date birthday;

    public UserServiceImpl() {
    
    
    }

    public UserServiceImpl(String name, Integer age, Date birthday) {
    
    
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void queryAll() {
    
    
        System.out.println(name+","+age+","+birthday+".");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45925906/article/details/112748256