spring的注解配置你知道吗?
发布日期:2021-05-08 01:13:25 浏览次数:19 分类:精选文章

本文共 2261 字,大约阅读时间需要 7 分钟。

1、    导包     4+2+1

aop:Spring-aop-5.0.2-RELEASE.jar

2、    导入约束文件

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context.xsd

3、    指定扫描的包

<!--扫描指定的位置 自动扫描该包以及该包所有的子包-->

<context:component-scanbase-package="cn.hd.annotation"></context:component-scan>

4、为类声明注解

/*相当于在.xml中写了bean  name-user class-cn.hd.annotation.User*/

@Component("user")

/*控制层,对应的是web层*/

@Controller("user")
/*service层*/
@Service("user")
/*dao层*/
@Repository("user")

publicclass User {

    private String name;
    private String age;
    private String address;
    private Car car;

为了解决所有的bean类都是同一个注解,所以提出了三个新的注解。

/*控制层,对应的是web层*/

@Controller("user")

/*service层*/
@Service("user")
/*dao层*/
@Repository("user")

没有强制要求,都可以用,提倡按照他的本意去注解。

修改scope属性

/*修改Scope属性*/

@Scope(scopeName= "protoype")       ß单例和多例模式à

5、属性注入

(1)、值类型

注解写在属性上面,同时也可以写在set方法上面。

@Value("张收纳")

private Stringname;

@Value("18")
private String age;
@Value("嘉兴")
private String address;

(2)、引用类型

/*@Autowired//自动装配

*//*当配置文件出现多个car时,要与自动装配配合使用*//*

@Qualifier("car2")*/

/*代替上面两步*/
@Resource(name = "car")
private Car car;

@Autowired:自动装配,如果只有一个对象,自动装配

@Qualifier("car2"):自动装配时有多个对象,就要指定是哪个对象,与自动装配结合使用。

@Resource(name = "car"):代替上两步,直接指定配置那个对象

(3)、创建对象后执行的方法

/*自动创建*/

@PostConstruct

public void init(){
    System.out.println("对象创建后执行。");
}
@PreDestroy
public void destroy(){
    System.out.println("对象销毁前创建。");
}

Spring结合Junit

1、导包

       Spring-test-5.0.2-RELEASE.jar

2、书写测试代码

/*声明Spring与Junit相结合*/

@RunWith(SpringJUnit4ClassRunner.class)

/*读取配置文件*/
@ContextConfiguration("classpath:cn/hd/annotation/applicationContext.xml")

  由于原来使用的是ApplicationContext对象,来读取配置和获得bean对象,但是现在没有了,又想获得对象

package cn.hd.annotation;

import org.junit.Test;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/*声明Spring与Junit相结合*/
@RunWith(SpringJUnit4ClassRunner.class)
/*读取配置文件*/
@ContextConfiguration("classpath:cn/hd/annotation/applicationContext.xml")
public class Demo1 {
    @Resource(name= "user")
   
private User user;
    @Resource(name = "userDao")
    private UserDao userDao;
    @Test
    public void fun(){
        System.out.println(user);
        System.out.println(userDao);
    }
}

上一篇:【Hive】函数 instr 的用法
下一篇:阿里面试题:Kafka 是如何保证数据可靠性和一致性

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月28日 13时52分27秒