8.使用注解开发

Bean的实现

之前是使用 bean 的标签进行bean注入,但在实际开发中我们一般都会使用注解

配置扫描哪些包下的注解

<context:component-scan base-package="com.dream.pojo"/>

在指定包下编写类,增加注解,将这个类交给Spring管理装配

@Component("user")
public class User {
    public String name = "张三";
}

测试

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) context.getBean("user");
        System.out.println(user.name);

使用注解注入属性

不用提供set方法,直接在属性名上添加@value(“值”)

@Component("user")
public class User {
    @Value("张三")
    public String name ;
}

如果提供了set方法,在set方法上添加@value(“值”);

@Component("user")
public class User {
    public String name ;
    @Value("张三")
    public void setName(String name) {
        this.name = name;
    }
}

衍生注解

@Component三个衍生注解:@Controller:web层,@Service:service层,@Repository:dao层

自动装配注解在上一篇已经讲过

作用域注解@scope

singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁。
prototype:多例模式。关闭工厂 ,所有的对象不会销毁,内部的垃圾回收机制会回收

使用配置类进行配置

新建实体类

package com.dream.pojo;

import org.springframework.stereotype.Component;

@Component
public class Dog {
    public String name = "旺财";
}

配置类

package com.dream.config;

import com.dream.pojo.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
public class MyConfig {
    @Bean
    public Dog dog(){
        return new Dog();
    }
}

测试

import com.dream.config.MyConfig;
import com.dream.pojo.Dog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        Dog dog = (Dog) context.getBean("dog");
        System.out.println(dog.name);
    }
}

若还有其他配置类

package com.dream.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig2 {
}

导入即可

@Import(MyConfig2.class)

实际开发中我们可以用xml管理bean,用注解注入属性

如果不扫描包,就需要手动配置bean,如果不加注解驱动,则注入的值为null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值