Creating a locked custom field in a plugin

I know how to create a custom field type in a plugin, but how do I directly add a custom field with a plugin?

Am I suppsoed to invoke CustomFieldManager to create it or is there a tag for it in atlassian-plugin.xml? Is there a way to listen to the plugin enabled event to do this?

Also how can I set that custom field to be locked?

i.e. I want to create something similar to Service Management’s SLA field, admins don’t need to add this custom field manually and the field is locked.

I found out about Atlassian Spring Scanner.

So I can create a class annotated with @Component so that it will be constructed… then I can create the custom field there.

However, it seems the timing is problematic. It seems when the constructor is called, Jira has completed loading my custom field type, so when I tried to find it using CustomFieldManager.getCustomFieldType(), it returns null.

How can I delay the component construction to create the custom field?

Found this:
https://developer.atlassian.com/server/jira/platform/writing-jira-event-listeners-with-the-atlassian-event-library/

So I can listen to a PluginEnabledEvent with that.

When the event listener is called, the plugin is already enabled and custom field type registered. Then I can look up if my custom field is there, and create it if not.

Creating a custom field programmatically is another can of worms, but luckily one I have already solved.

Only locking it left. It should be something about permission, as the way to check if a custom field is locked or not is:

	final ManagedConfigurationItemService CONFIG_ITEM_SERVICE = 
		ComponentAccessor.getComponent(ManagedConfigurationItemService.class);

			ManagedConfigurationItem item = CONFIG_ITEM_SERVICE.getManagedCustomField(cf);
			ApplicationUser currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
			return !CONFIG_ITEM_SERVICE.doesUserHavePermission(currentUser, item);

So making a field locked should be along those lines.

Edit:
https://docs.atlassian.com/software/jira/docs/api/8.21.0/com/atlassian/jira/config/managedconfiguration/ManagedConfigurationItemBuilder.html

The builder can set access level, one of which is LOCKED.

// Lock the custom field
				ManagedConfigurationItemService configItemService = 
						ComponentAccessor.getComponent(ManagedConfigurationItemService.class);
				ManagedConfigurationItem item = configItemService.getManagedCustomField(created);
				ManagedConfigurationItemBuilder builder = item.newBuilder();
				item = builder
						.setConfigurationItemAccessLevel(ConfigurationItemAccessLevel.LOCKED)
						.setManaged(true)
						.build();
				configItemService.updateManagedConfigurationItem(item);