Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

nacos-spring-project

> 后端框架
Open source

Nacos ECO Project for Spring Framework

766 stars0 likes1 views
WebsiteGitHub

About

Nacos ECO Project for Spring Framework

Nacos Spring Project

Nacos is an open source project for discovering, configuring and managing cloud-native applications. Key features of Nacos include:

  • Service Discovery and Service Health Check
  • Dynamic Configuration Management
  • Dynamic DNS Service
  • Service and Metadata Management

Nacos Spring Project, which is based on Nacos, fully embraces the Spring ecosystem and is designed to help you build Spring applications rapidly.

The project contains a core module named nacos-spring-context. It enables you to expand modern Java programming models in the following ways:

  • Annotation-Driven
  • Dependency Injection
  • Externalized Configuration
  • Event-Driven

These features strongly depend on Spring Framework 3.2+ API, and can be seamlessly integrated with any Spring Stack, such as Spring Boot and Spring Cloud.

Note: We recommend that you use annotation-driven programming, even though XML-based features also work.

Content

  • 1. Samples
    • 1.1. Samples
    • 1.2. How To Run the Samples
  • 2. Dependencies & Compatibility
  • 3. Quickstart
    • 3.1. Prerequisite
    • 3.2. Enable Nacos
    • 3.3. Enable configuration service
    • 3.4. Enable Service Discovery
  • 4. Core Features
    • 4.1. Annotation-Driven
      • 4.1.1. Enable Nacos
      • 4.1.2. Configure Change Listener method
        • 4.1.2.1. Type Conversion
          • [4.1.2.1.1. Type Conversion during YAML Parsing](#41211-Type Conversion during YAML Parsing)
        • 4.1.2.2. Timeout of Execution
      • 4.1.3. Global and Special Nacos Properties
      • 4.1.4. @NacosProperties
    • 4.2. Dependency Injection
    • 4.3. Externalized Configuration
    • 4.4. Event/Listener Driven
  • 5. Modules
  • 6. Relative Projects

1. Samples

Included in this section are some samples for you to get a quick start with Nacos Spring.

1.1. Samples

  • Dependency Injection Sample of @NacosInjected

  • Simple Sample of @NacosConfigListener

  • Type Conversion Sample of @NacosConfigListener

  • Timeout Sample of @NacosConfigListener

  • Sample of @NacosConfigurationProperties/@NacosProperty/@NacosIgnore

  • Sample of @NacosPropertySources/@NacosPropertySource

  • Event/Listener Sample

1.2. How To Run the Samples

Take the Spring Web MVC project for example:

  1. Check out the source code of nacos-spring-project :

    $ git clone [email protected]:nacos-group/nacos-spring-project.git

  2. Build your source code with Maven:

    $ mvn clean package

  3. Run Spring Web MVC Samples:

    $ java -jar target/nacos-spring-webmvc-sample.war

2. Dependencies & Compatibility

The following table shows the dependencies and compatabilities of Nacos Spring Project.

Dependencies Compatibility
Java 1.8+
Spring Context 3.2+
Alibaba Spring Context Support 1.0.1+
Alibaba Nacos 1.1.1+

3. Quickstart

This quickstart shows you how to enable Nacos and its service discovery and configuration management features in your Spring project.

3.1. Prerequisite

Before you configure your Spring project to use Nacos, you need to start a Nacos server in the backend. Refer to Nacos Quick Start for instructions on how to start a Nacos server.

3.2. Enable Nacos

Complete the following steps to enable Nacos for your Spring project.

  1. Add nacos-spring-context in your Spring application's dependencies:

    xml
        
            ...
            
            
                com.alibaba.nacos
                nacos-spring-context
                1.1.0
            
            
            ...
        

Note: Support Spring 5 from version 0.2.3-RC1, support Spring 6 from version 2.1.0.

  1. Add the @EnableNacos annotation in the @Configuration class of Spring and specify "${host}:${port}" of your Nacos server in the serverAddr attribute:

    java
    @Configuration
    @EnableNacos(
            globalProperties =
            @NacosProperties(serverAddr = "${nacos.server-addr:localhost:12345}")
    )
    public class NacosConfiguration {
        ...
    }

3.3. Enable configuration service

Now you would like to use the confguration service of Nacos. Simply use Dependency Injection to inject ConfigService instance in your Spring Beans when @EnableNacos is annotated, as shown below:

java
@Service
public class ConfigServiceDemo {

    @NacosInjected
    private ConfigService configService;
    
    public void demoGetConfig() {
        try {
            String dataId = "{dataId}";
            String group = "{group}";
            String content = configService.getConfig(dataId, groupId, 5000);
        	System.out.println(content);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
    ...
}

ConfigService is the key interface of Nacos which helps you to get or publish configurations.

The following code achieves the same effect:

…

3.4. Enable Service Discovery

If you would also like to use the service discovery feature of Nacos, you can inject a NamingService instance for service discovery:

java
    @NacosInjected
    private NamingService namingService;

For details about the usages of ConfigService and NamingService, please refer to Nacos SDK.

4. Core Features

This section provides a detailed description of the key features of nacos-spring-context:

  • Annotation-Driven
  • Dependency Injection
  • Externalized Configuration
  • Event-Driven

4.1. Annotation-Driven

4.1.1. Enable Nacos

@EnableNacos is a modular-driven annotation that enables all features of Nacos Spring, including Service Discovery and Distributed Configuration. It equals to @EnableNacosDiscovery and @EnableNacosConfig, which can be configured separately and used in different scenarios.

4.1.2. Configure Change Listener method

Suppose there was a config in Nacos Server whose dataId is "testDataId" and groupId is default group("DEFAULT_GROUP"). Now you would like to change its content by using the ConfigService#publishConfig method:

java
    @NacosInjected
    private ConfigService configService;

    @Test
    public void testPublishConfig() throws NacosException {
        configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527");
    }

Then you would like to add a listener, which will be listening for the config changes. You can do this by adding a config change listener method into your Spring Beans:

java
    @NacosConfigListener(dataId = DATA_ID)
    public void onMessage(String config) {
        assertEquals("mercyblitz", config); // asserts true
    }

The code below has the same effect:

java
	configService.addListener(DATA_ID, DEFAULT_GROUP, new AbstractListener() {
        @Override
        public void receiveConfigInfo(String config) {
            assertEquals("9527", config); // asserts true
        }
    });

Note: @NacosConfigListener supports richer type conversions.

  • See Simple Sample of @NacosConfigListener

4.1.2.1. Type Conversion

The type conversion of @NacosConfigListener includes both build-in and customized implementations. By default, build-in type conversion is based on Spring DefaultFormattingConversionService, which means it covers most of the general cases as well as the rich features of the higher Spring framework.

For example, the content "9527" in the preceding example can also be listened by a method with integer or the Integer argument:

java
    @NacosConfigListener(dataId = DATA_ID)
    public void onInteger(Integer value) {
        assertEquals(Integer.valueOf(9527), value); // asserts true
    }

    @NacosConfigListener(dataId = DATA_ID)
    public void onInt(int value) {
        assertEquals(9527, value); // asserts true
    }

Of course, nacos-spring-context provides elastic extension for developers. If you define a named nacosConfigConversionService Spring Bean whose type is ConversionService , the DefaultFormattingConversionService will be ignored. In addition, you can customize the implementation of the NacosConfigConverter interface to specify a listener method for type conversion:

java
public class UserNacosConfigConverter implements NacosConfigConverter {

    @Override
    public boolean canConvert(Class targetType) {
        return true;
    }

    @Override
    public User convert(String source) {
        return JSON.parseObject(source, User.class);
    }
}

The UserNacosConfigConverter class binds the @NacosConfigListener.converter() attribute:

java
	@NacosInjected
    private ConfigService configService;

	@Test
    public void testPublishUser() throws NacosException {
        configService.publishConfig("user", DEFAULT_GROUP, "{\"id\":1,\"name\":\"mercyblitz\"}");
    }

    @NacosConfigListener(dataId = "user", converter = UserNacosConfigConverter.class)
    public void onUser(User user) {
        assertEquals(Long.valueOf(1L), user.getId()); 
        assertEquals("mercyblitz", user.getName());
    }
4.1.2.1.1. Type Conversion during YAML Parsing

By default, starting from version 1.1.2

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javadistributed-configurationjavanacosspring

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架