Springboot使用bean方式详解(附代码)

上一章节中介绍了springboot创建bean的几种方式:注解形式(@Controller/@Service/@Component/@Repository)和@Configuration/@Bean组合注解形式;
本章节主要介绍如何在项目中使用创建的bean。
#####范例一:通过Bean类、xml配置文件创建bean并注入到容器中

//创建bean类
public class Computer {
    private String name;
    private String color;
    private Float price;

    public String getName() {
        return name;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Computer{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }
}
<!--------通过applicationContext.xml配置文件实例化bean并注入Spring容器中-------->
<beans>
	<bean id="computer" class="com.java.demo.Computer">
		<property name="name" value="联想"></property>
		<property name="color" value="黑色"></property>
		<property name="price" value="6500.45"></property>
	</bean>
</beans>
public class Test{
	//单元测试:创建context容器并从容器中根据bean的id值获取bean,并打印出来
	@Test
	public void testBean(){
		ApplicationContext context = new ClassPathXmlApplicaitonContext("applicationContext.xml");
		Computer c = context.getBean("computer",Computer.class);
		System.out.println(c);
	}
}

#####范例二:通过bean类、@Configuration/@Bean组合注解实现创建bean并注入到容器中

//创建bean类,同范例一
public class Computer {
    private String name;
    private String color;
    private Float price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Computer{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }
}
//通过该配置类的编写实现创建bean并注入到spring容器中
@Configuration
public class BeanConfig{
	//Bean注解若不带name参数,则默认以方法名getComputer为bean的id,用于后续获取bean;若带参数则以name参数名用于后续获取bean
	@Bean(name="computer")
	public Computer getComputer(){
		Computer com = new Computer();
		com.setName("联想");
		com.setColor("红色");
		com.setPrice(6500.55);
		return com;
	}
}
public class Test{
    //单元测试:创建context容器并从容器中根据bean的id值获取bean,并打印出来
    @Test
    public void testBean(){
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
		//Computer c = context.getBean(Computer.class)该种方式也可以从容器中获取bean,同下
        Computer c = context.getBean("computer",Computer.class);
        System.out.println(c);
    }
}

#####范例三:通过@Component等注解方式创建bean并注入容器,再通过@AutoWired或@Resource注解实现依赖注入,自动装配(取出bean)。这是我们在springboot项目中最常用的使用bean的方式,前两种使用bean的方式偏重于原理性和底层,项目中这样使用的情况不多;话不多说,直接上代码:

//@Service(是@Component的注解的子类)注解表示当前类对象是一个bean,在程序运行时会被spring容器扫描到并注入到容器中,这一步相当于创建bean的过程
@Service
public class ServiceImpl implements Service{
	@OVerride
	public void print (){
		System.out.println("我是实现类");
	}
}
//进行单元测试,@SpringBootTest注解代表是一个单元测试类的程序入口。
@SpringBootTest
public class DemoApplicationTests {
	//@AutoWired注解可以自动取出容器中的bean(Service接口的实现类的对象),根据类型自动装配,此处也可使用@Resource注解
    @Autowired
    private Service service;

    @Test
    public void testBean() {
        service.print();
    }
}

#####范例四:通过@Configuration和@Bean组合注解创建bean并注入容器,再通过@AutoWired或@Resource注解实现依赖注入,自动装配(取出bean),代码如下:

//组合注解创建bean并注入容器,前面已经讲过了,不再赘述。
@Configuration
public class BeanConfig{
	@Bean
	public Computer getComputer(){
		Computer computer = new Computer();
		computer.setName("macBook");
		computer.setBrand("苹果")
		computer.setColor("白色");
		computer.setPrice(1600050f);
		return computer;
	}
}

//进行单元测试,@SpringBootTest注解代表是一个单元测试类的程序入口。
@SpringBootTest
public class DemoApplicationTests {
    //@AutoWired注解可以自动取出容器中的bean(Service接口的实现类的对象),根据类型自动装配,此处也可使用@Resource注解
    @Autowired
    private Computer computer;
    @Test
    public void testBean() {
        System.out.println(computer);
    }
}
//注意:@AutoWired、@Resource要实现自动装配(取出bean)的前提是bean对象所属的类要
//被spring容器扫描到,如果扫描不到,容器中就不会注入bean,更不用说取出bean了,所以主
//程序入口要放到最外层,这样才能扫描到它的平级及子级中的被注解修饰的类;单元测试中,也
//要保证测试程序的主类能扫描到所要测试的被注解修饰的类。

原博文链接:http://www.54gwz.cn/article/1591256016

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot是一个用于快速构建基于Spring框架的Java应用程序的开发框架。MQTT(Message Queuing Telemetry Transport)是一种轻量级的消息传输协议,通常用于物联网设备之间的通信。 在Spring Boot中整合MQTT协议,可以使用 Eclipse Paho客户端库来实现。以下是详细的整合步骤: 1. 添加依赖:在项目的pom.xml文件中添加Eclipse Paho的MQTT依赖。例如: ```xml <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> ``` 2. 创建MQTT配置类:创建一个用于配置MQTT连接的类。例如: ```java @Configuration public class MqttConfig { @Value("${mqtt.broker}") private String broker; @Value("${mqtt.clientId}") private String clientId; @Bean public MqttClient mqttClient() throws MqttException { MqttClient mqttClient = new MqttClient(broker, clientId); mqttClient.connect(); return mqttClient; } } ``` 在上述代码中,使用了`@Value`注解来读取配置文件中的MQTT服务器地址和客户端ID。 3. 发布消息:可以在需要发布消息的地方注入`MqttClient`并使用它来发布消息。例如: ```java @Service public class MqttPublisher { @Autowired private MqttClient mqttClient; public void publish(String topic, String message) throws MqttException { mqttClient.publish(topic, new MqttMessage(message.getBytes())); } } ``` 4. 订阅消息:可以创建一个实现`MqttCallback`接口的类来处理订阅消息。例如: ```java @Component public class MqttSubscriber implements MqttCallback { @Autowired private MqttClient mqttClient; @Override public void connectionLost(Throwable cause) { // 处理连接丢失的情况 } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // 处理接收到的消息 } @Override public void deliveryComplete(IMqttDeliveryToken token) { // 处理消息传递完成的情况 } @PostConstruct public void subscribe() throws MqttException { mqttClient.setCallback(this); mqttClient.subscribe("topic"); } } ``` 在上述代码中,使用了`@Component`注解将该类声明为Spring组件,并在`@PostConstruct`方法中订阅了名为"topic"的主题。 这就是整合Spring Boot和MQTT协议的基本步骤。通过配置MQTT连接和使用相应的客户端库,您可以轻松地在Spring Boot应用程序中实现MQTT通信。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值