欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring使用注解开发

程序员文章站 2022-07-08 08:36:19
...

首先我们要先配置好对应的ApplicationContext.xml,填写好组件扫描,然后就无需在xml中声明bean也能正常运行了。

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

    <!--启用包扫描-->
    <context:component-scan base-package="com.spring"/>
    <!--启用注解-->
    <context:annotation-config/>

</beans>



1. @Component

在对应的实体类上声明@Component注解即可将类注册为一个组件,从而被Spring扫描到。

@Component
public class User {
    private String name;

    public User() {
        super();
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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



2. @Value

@Value()注解可以为属性注入值

	@Value("jack")
    private String name;



3. @Repository

@Repository跟@Component作用相同,但Repository一般是加在mapper层上的注解

@Repository
public interface UserMapper {

}



4. @Service

@Service跟@Repository作用相同,都是加在mapper层上的注解

@Service
public interface UserMapper {

}



5. @Controller

@Controller跟@Service,@Repository,@Component作用相同,但却是加在controller层上的注解

@Controller
public class UserController {
}



6. @Scope

@Scope指定在类上声明作用域

@Component
@Scope("singletion")
public class User {

    @Value("jack")
    private String name;

    public User() {
        super();
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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



相关标签: Spring spring